2017-01-30 67 views
0

我想圍繞Angular 2中的observables如何工作而不是將它們用作模式。如果我像下面那樣創建一個基本的可觀察元素,我可以調用source變量的subscribe方法,該變量是創建observable並將其賦值給source變量的結果。Observable如何在Angular 2中工作

let numbers = [19, 38, 57]; 
let source = Observable.from(numbers); 

source.subscribe(
    value => console.log(`value: ${value}`), 
    error => console.log(`error: ${error}`), 
() => console.log('complete') 
); 

在角2 I有以下代碼:

組件:

private getDevicesByUserId(): void { 
    this.devicesHttp.getDevicesByUserId(this.userID) 
    .subscribe(
     data => { 
     this.devices = data; 
     }, 
     error => {}, 
    () => {} 
    ); 
} 

HTTP服務:

public getDevicesByUserId(userID: number): Observable<any> { 
    return this.http.get(this.url + 'api/device/user/' + userID, { 
    headers: this.httpHeaders.getHeaders() 
    }) 
    .map((response) => this.handleData(response)) 
    .catch((error) => this.handleError(error)); 
} 

在上面的模式中,我調用了getDevicesByUserId函數的subscribe方法,但在http中沒有創建可觀察對象。也許我錯過了一些東西,但它只是一個返回http調用結果的函數。我如何能夠像這樣的常規功能調用訂閱方法?如果我沒有創建一個observable,函數如何具有這個屬性?

回答

0

Angular 2 Http service函數getpost是內置的返回一個冷的Observable返回一個響應。

您不必顯式創建Observable。如果您願意,可以通過http代碼here

作爲一個冷觀察者,請求本身在觀察者訂閱時發送。 更多關於hot and cold observable here 您的getDevicesByUserId在您自己的服務中返回您最終在組件中訂閱的相同觀察值。

希望這會清除它。

+0

是的,非常感謝。 – Aaron