2015-12-29 173 views
3

希望有人能为我澄清一些事情。 我在做什么,现在,具有角1.4.6工作:Angular 2 HTTP GET相当于Angular HTTP GET

我创建服务

'use strict'; 
angular.module('App') 
.factory('processingService', ['$http', 
    function ($http) { 
     var settings = 'Settings/GetSettings';  
     var getSettings = function() 
     { 
      return $http.get(settings) 
       .then(function(response) 
       { 
        return response.data; 
       }); 
     }; 
     return { 
      getSettings: getSettings   
     }; 
    } 
]); 

并使用/注射,在我的控制器。

'use strict'; 
angular.module('App') 
.controller('appController', [ 
    '$scope','appService', 
    function ($scope, appService) {  
     var onSettings = function (data) { 
      if (data.hasOwnProperty('Settings')) {  
       //Code handling Settings   
      } 
     }; 
     var onSettingsError = function() 
     { 
      //Handle Errors 
      $scope.showLoader = false; 
     };  
     appService.getSettings() 
      .then(onSettings, onSettingsError); 
}]); 

我开始一点点与angular2公测玩了一圈,发现在http.get

getRandomQuote() { 
    this.http.get('http://localhost:3001/api/random-quote') 
    .map(res => res.text()) 
    .subscribe(
     data => this.randomQuote = data, 
     err => this.logError(err), 
    () => console.log('Random Quote Complete') 
    ); 
} 

logError(err) { 
    console.error('There was an error: ' + err); 
} 

我建立了一些其他的方法,下面的例子和周围测试了一下,用Google搜索了很多,但能没有发现任何类似的创建服务与angular2测试版和打字稿我一直在做的方式。 甚至有必要这样做。 或者,这是不是现在与Angular2测试版的方式?

预先感谢您。

回答

2

您可以简单地从你的服务,即与Injectable注释类返回一个观察的对象(什么http.get方法返回):

@Injectable() 
export class CompanyService { 
    constructor(http:Http) { 
    this.http = http; 
    } 

    getRandomQuote() { 
    return this.http.get('http://localhost:3001/api/random-quote') 
        .map(res => res.json()); 
    } 
} 

在你的组件,你可以再注入此服务并调用实际执行HTTP请求的方法。为了得到结果,只需使用subscribe方法:

export class CompanyList implements OnInit { 
    public companies: Company[]; 

    constructor(private service: CompanyService) { 
    this.service = service; 
    } 

    logError(err) { 
    } 

    ngOnInit() { 
    this.service.getRandomQuote().subscribe(
     data => this.randomQuote = data, 
     err => this.logError(err), 
    () => console.log('Random Quote Complete') 
    ); 
    } 
} 

你可以在这个地址有更多的细节:How to Consume Http Component efficiently in a service in angular 2 beta?

希望它能帮到你, Thierry

0

角2中的服务只是用@Injectable()装饰的TypeScript类。

服务看起来是这样的:

import {Injectable, Inject, EventEmitter} from 'angular2/core'; 
import {Http, Response} from 'angular2/http'; 

@Injectable() // annotated class that can be injected in other components 
export class ProcessingService { 
    // inject the http service (configured in the global injector) 
    constructor(@Inject(Http) private http :Http) { 

    } 
    // the service method returning an event emmiter (instead of promises) 
    public getSettings():EventEmitter<string> { 

     let emmiter = new EventEmitter<string>(true); 

     // call the method and subscribe to the event emmiter 
     this.http.get('Settings/GetSettings').subscribe((value: Response) => { 
     emmiter.emit('called');  
     }); 
     return emmiter; 
    } 
} 

然后你可以使用依赖注入插入服务组件,像这样:

import {Component, Inject } from 'angular2/core'; 
// import our service 
import {ProcessingService} from './services/processing-service/processing-service'; 

@Component({ 
    selector: 'http-search-params-app', 
    providers: [], 
    templateUrl: 'app/http-search-params.html', 
    pipes: [], 
    bindings:[ProcessingService] // tell the component injector to inject our service 
}) 
export class HttpWorkApp { 
    workDone = []; 

    constructor(private processingService: ProcessingService) {} 

    // call the sevice 
    public doWork() { 
     this.processingService.getSettings().subscribe((value :string) =>{ 
      this.workDone.push(value); 
     }); 
    } 
} 

该组件的模板:

<div> 
    <button (click)="doWork()">Call HTTP Service</button> 
    <div *ngFor="#workItem of workDone">{{workItem}}</div>  
</div> 

您还需要配置全局注入以允许注入Http服务。

import {bootstrap} from 'angular2/platform/browser'; 
import {HttpWorkApp} from './app/http-search-params'; 
import {HTTP_PROVIDERS} from 'angular2/http'; 

bootstrap(HttpWorkApp, [HTTP_PROVIDERS]);