在Angular的subscription部分中使用时,方法不存在 [英] Method doesn't exists while using in subscribe section of Angular

查看:60
本文介绍了在Angular的subscription部分中使用时,方法不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. Angular:使用forkJoin调用两个服务方法
  2. 尝试使用订阅中的另一种方法处理结果
  3. 最后从流程方法中调用另一个方法
  4. 遇到错误,该方法不存在

这是代码:

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.

这是错误:

错误TypeError:this.validateData不是一个函数在SafeSubscriber.push ../projects/pathToComponentnst/xyzComponent.processData中[作为_next]

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

100%确定该方法存在,并且可用于其他方法,但仅在这种情况下,该方法不起作用.什么是SafeSubscriber.push有错误?

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?

只需在此处 https:复制相同的内容://stackblitz.com/... ,打开控制台以查看错误!

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

推荐答案

执行此操作时:

.subscribe(
    this.processData,
    ...

它更改了 processData 的范围,而新的范围没有 validateData 方法.您必须将其包装在箭头函数中以保留范围:

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),
    ...

或使用 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()

这篇关于在Angular的subscription部分中使用时,方法不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆