[英]Angular 2 : how to refer to a class variable inside a function called by Observable map
In an Angular 2 App that uses Observable
in a service, how can I refer a private field of the class inside map
? 在服务中使用
Observable
的Angular 2应用程序中,如何在map
引用类的私有字段? As illustrated in the code below, how can we refer to this._dataStore
inside the extractData
function? 如下面的代码所示,我们怎么可以参考
this._dataStore
里面extractData
功能? thanks! 谢谢!
Note that i did see this question that suggests putting the function body inside () => {function body here}
, but i'd really like to be able to call the function, especially that this logic will probably be used at other places (don't want to copy and paste it all over the places.) 请注意,我确实看到这个问题建议将函数体放在
() => {function body here}
,但我真的希望能够调用该函数,特别是这个逻辑可能会在其他地方使用(不想将它们复制并粘贴到所有地方。)
@Injectable()
export class DataService{
constructor(private http: Http){}
private _dataStore = [];
getData(): Observable<any> {
if(this._dataStore.length > 0) { //return cached data
return Observable.of(this._dataStore);
} else {
return this.http.get('url')
.map(this.extractData)
.catch(this.handleError);
}
}
private extractData(res: Response){
if(res.status < 200 || res.status >= 300){
throw new Error('Bad response status '+ res.status);
}
var data = res.json();
for (var i in data['items']){
this._dataStore.push(data['items'][i]); //ERROR this._dataStore undefined
}
return this._dataStore;
}
You can wrap the entire call to extractData
in an arrow function: 您可以在arrow函数
extractData
的整个调用包装起来:
this.http.get("url")
.map(data => this.extractData(data))
.catch(err => this.handleError(err))
Notice I did the same for this.handleError
. 注意我对
this.handleError
做了同样的this.handleError
。 This technique will maintain your reference to this
during your call. 这项技术将在您通话期间保持您
this
的参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.