Angular 2: how to refer to a class variable inside a function called an observable map

In an Angular 2 application that uses Observablein a service, how can I refer to a private field of a class inside map? As shown in the code below, how can we refer to this._dataStoreinside a function extractData? thank!

Please note that I saw this question , which suggests placing the body of the function inside () => {function body here}, but I would really like to be able to call the function, especially that this logic will probably be used in other places (do not want to copy and paste it in all 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();
    for (var i in data['items']){
      this._dataStore.push(data['items'][i]); //ERROR this._dataStore undefined
    }
    return this._dataStore;
  }
+4
source share
1

extractData :

this.http.get("url")
         .map(data => this.extractData(data))
         .catch(err => this.handleError(err))

, this.handleError. this .

+5

All Articles