代码之家  ›  专栏  ›  技术社区  ›  Guerrilla

角度订阅中的方法调用超出组件属性的范围

  •  0
  • Guerrilla  · 技术社区  · 7 年前

    我有一个在我的组件的不同位置调用的方法,如下所示:

    this.updateResults();
    

    此方法依赖于组件上的几个属性。该方法在从模板调用的方法中运行良好,但我希望它在queryParams更改后工作,因此我使用以下代码:

      ngOnInit() {
        this.navigationSubscription = this._router.events.subscribe((e: any) => {
          if (e instanceof NavigationEnd) {
            this.updateResults();
          }
        });
      }
    

    该方法在预期的时间执行,但我可以在调试器中看到,当它执行时,所需的属性为null。

    _this 而不是 this this.propertyName 我想这不管用。

    1 回复  |  直到 7 年前
        1
  •  2
  •   andreas    7 年前

    您可以尝试以下方法:

    ngOnInit() {
        const _this = this;
        this.navigationSubscription = this._router.events.subscribe((e: any) => {
            if (e instanceof NavigationEnd) {
                _this.updateResults();
            }
        });
    }
    

    我不确定在您的案例中,范围是否真的是一个问题,但这种方法有时已经救了我。

    推荐文章