简体   繁体   English

Angular 2服务:为什么私有成员未定义?

[英]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. 从服务中的另一个功能,当我尝试读取this.data时,它是未定义的。 Why? 为什么?

    getData() {

         this.data // undefeind !!!!
}

From a component there is a call to the service to getData onInit: 从组件可以调用该服务以调用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 如果要在传递的方法中访问this方法,则需要绑定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. 在此用例中, bind(this)() => {}更方便,因为不管需要传递多少参数,它都可以工作。 With arrow functions all parameters need to be repeated twice. 使用箭头功能时,所有参数都需要重复两次。

@Gunther's solution works. @Gunther的解决方案有效。 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));
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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