Method doesn't exists while using in subscribe section of Angular

懵懂的女人 提交于 2021-01-28 21:02:53

问题


  1. Angular: calling two service method with forkJoin
  2. Try to process the result in another method in subscription
  3. Finally calling another method from process method
  4. and getting error, that method doesn't exists

Here is the code:

onLoad(){
  forkJoin([
    this.service1.getData(),
    this.service2.fetchData(id)
  ]).subscribe(
    this.processData,
    errors => { this.error = true; }, 
    () => { this.loading = false; })
};

processData(response: any){
   recordA = response[0];
   recordB = response[1];
   this.validateData(recordB);
}

validateData(record: any) {
  ... some code here ...
}

Note: both the service returning result properly, I check the data.

Here is the error:

ERROR TypeError: this.validateData is not a function at SafeSubscriber.push../projects/pathToComponentnst/xyzComponent.processData [as _next]

100% sure method is there and working for other methods but only in this scenario it is not working. What is the SafeSubscriber.push there is error?

Just reproduce the same here https://stackblitz.com/..., open console to see the error!


回答1:


When you do this:

.subscribe(
    this.processData,
    ...

it changes the scope of processData, and the new scope doesn't have a validateData method. You have to wrap it in an arrow function to preserve the scope:

.subscribe(
    response => this.processData(response),
    ...

or use bind:

.subscribe(
    this.processData.bind(this),
    ...

Here's a snippet to demonstrate the behavior:

class MyClass {
  constructor () {
    this.funcOne(() => this.funcTwo()) // works
    this.funcOne(this.funcTwo.bind(this)) // works
    this.funcOne(this.funcTwo) // what you're doing, doesn't work
  }
  
  funcOne (func) {
    func()
  }
  funcTwo () {
    this.funcThree()
  }
  funcThree () {
    console.log("success")
  }
}

new MyClass()



回答2:


don't you need to pass processData an argument. otherwise validateData has nothing to validate.



来源:https://stackoverflow.com/questions/60403280/method-doesnt-exists-while-using-in-subscribe-section-of-angular

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!