问题
- Angular: calling two service method with forkJoin
- Try to process the result in another method in subscription
- Finally calling another method from process method
- 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