2016-05-31 85 views
1

我在Angular2中使用Typescript。我已經訂閱了從下面的代碼的HTTP請求的響應:在Angular2中調用的方法失序。如何正確訂閱?

search(searchTerm): void { 
    this._webservice.getSearchResult(searchTerm).subscribe(results => this.results = results); 
    this.callThisMethod(); 
} 

我希望發生的是更新this.results的值,然後調用this.callThisMethod()變量已更新後。 this.callThisMethod()正在被調用失序。如何在變量更新後運行該方法?

回答

2

一旦響應可用,而不是同步,Observable的訂閱將被異步調用。如果只想要this.callThisMethod(),那麼需要將其作爲異步回調的一部分:

search(searchTerm): void { 
    this._webservice.getSearchResult(searchTerm) 
     .subscribe(results => { 
      this.results = results; 
      this.callThisMethod(); 
     }); 
}