Angular 2 服务:为什么私有成员未定义?
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));
}
试图弄清楚为什么如果我设置了服务的私有成员,当我返回该服务时我会发现该成员未定义。
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));
}