javascript - Angular 2 : how to refer to a class variable inside a function called by Observable map -
in angular 2 app uses observable
in service, how can refer private field of class inside map
? illustrated in code below, how can refer this._datastore
inside extractdata
function? thanks!
note did see this question suggests putting function body inside () => {function body here}
, i'd able call function, logic used @ other places (don't want copy , paste on places.)
@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(); (var in data['items']){ this._datastore.push(data['items'][i]); //error this._datastore undefined } return this._datastore; }
you can wrap entire call extractdata
in arrow function:
this.http.get("url") .map(data => this.extractdata(data)) .catch(err => this.handleerror(err))
notice did same this.handleerror
. technique maintain reference this
during call.
Comments
Post a Comment