简体   繁体   中英

Angular 2 service: Why the private member is undefined?

Trying to figure out why If I set a private member of a service, when I get back to that service I will find out that the member is undefined.

getResult (): Observable<result[]> {
    return this.http.get(this.url)
      .map(this.extractData)
      .catch(this.handleError);
  }


  private extractData(res: Response) {
    let body = res.json();

    // save the data in the service
    this.data = body;

    return body || { };
  }

From another function in the service, when I try to read this.data it is undefined. Why?

    getData() {

         this.data // undefeind !!!!
}

From a component there is a call to the service to getData onInit:

 this.myService.getResult()
      .subscribe(res => {this.data= res;
        },
        error => {
          console.log("error on getData function: " + error);
        }
      );

If you want to access this within the passed method you need to bind this

.map(this.extractData.bind(this))

bind(this) is IMHO more convenient for this use case than () => {} because it works, no matter how many parameters need to be passed. With arrow functions all parameters need to be repeated twice.

@Gunther's solution works. Another way to solve is to wrap in arrow functions.

getResult (): Observable<result[]> {
    return this.http.get(this.url)
      .map((res)=>this.extractData(res))
      .catch((err)=>this.handleError(err));
  }

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