简体   繁体   中英

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 ? As illustrated in the code below, how can we refer to this._dataStore inside the extractData function? 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.)

@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:

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

Notice I did the same for this.handleError . This technique will maintain your reference to this during your call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM