Observed change in area in a method called a map operator

I tried to change my data before returning it in the method called by the map operator, and found that all my other variables outside this method are not undefined

I wrote simple code here to introduce what I mean, the registered test variable is returned as undefined :

 import {Observable} from "rxjs/Observable"; import {Injectable} from "@angular/core"; import {Http, Response} from "@angular/http"; @Injectable() export class DataService { private API_URL= 'url...'; private test = 1; constructor(private http: Http) {} getData(): Observable<any> { return this.http.get(this.API_URL) .map(this.extractData) .catch(this.handleError); } private extractData(res: Response) { let body = res.json(); console.log(test); return body.data || {}; } } 

I wanted to know why this is happening, and if this is not a way to change the extracted data, how can I do it in the service (not in the subscriber component, because I want to change the data based on another variable that has nothing to do with the subscriber component)

+7
source share
1 answer

This is the "JS" function ,-)

You need to use .bind(this)

  return this.http.get(this.API_URL) .map(this.extractData.bind(this)) .catch(this.handleError.bind(this)); 

or arrow functions

  return this.http.get(this.API_URL) .map(val => this.extractData(val)) .catch(err => this.handleError(err)); 

to save this area

+7
source

All Articles