2015-12-29 172 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]);