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

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -