![](/img/trans.png)
[英]Injected service is undefined in derived class if private variable is initialized (Angular 2, TypeScript)
[英]Angular 2 service: Why the private member is undefined?
試圖弄清原因如果我設置服務的私有成員,當我返回該服務時,我會發現該成員是未定義的。
getResult (): Observable<result[]> {
return this.http.get(this.url)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
// save the data in the service
this.data = body;
return body || { };
}
從服務中的另一個功能,當我嘗試讀取this.data時,它是未定義的。 為什么?
getData() {
this.data // undefeind !!!!
}
從組件可以調用該服務以調用getData onInit:
this.myService.getResult()
.subscribe(res => {this.data= res;
},
error => {
console.log("error on getData function: " + error);
}
);
如果要在傳遞的方法中訪問this
方法,則需要綁定this
.map(this.extractData.bind(this))
在此用例中, bind(this)
比() => {}
更方便,因為不管需要傳遞多少參數,它都可以工作。 使用箭頭功能時,所有參數都需要重復兩次。
@Gunther的解決方案有效。 解決的另一種方法是包裝箭頭函數。
getResult (): Observable<result[]> {
return this.http.get(this.url)
.map((res)=>this.extractData(res))
.catch((err)=>this.handleError(err));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.