【问题标题】:Ionic, Angular - ChangeDetectorRef is undefined离子,角度 - ChangeDetectorRef 未定义
【发布时间】:2019-05-08 23:16:59
【问题描述】:

我正在像这样导入 ChangeDetectorRef:

import { Component, ViewChild, ChangeDetectorRef , ElementRef } from '@angular/core';

并像这样在我的页面的构造函数中初始化更改检测器:

constructor(
    ...
    private ref: ChangeDetectorRef
  )

但是当我在回调函数中执行 detectChanges() 时:

 hardResetCallback(car:Car){
    this.car=car;
    this.ref.detectChanges();
  }

它说“无法读取未定义的属性 'detectChanges'”。我可能会错过什么?

编辑:

回调是从模态调用的。模态通过导航参数获取回调 - 在我调用的父组件中:

const resetModal : Modal = this.modal.create('CarConfigurationResetPage', { car: this.car, callback: this.hardResetCallback });
    resetModal.present();

然后这就是我在模态中的获取方式:

 this.callback=this.navParams.get('callback');

我在 AJAX 调用的成功方法中从模态调用回调,如下所示:

this.callback(response);

【问题讨论】:

  • 您如何以及何时致电hardResetCallback()
  • 阿米特 - 见编辑
  • 所以我明白回调中的“this”变量是指模态,而不是父组件。如何在回调中引用父组件?
  • 为什么不将this 绑定到您的this.modal.create()
  • 试试const resetModal : Modal = this.modal.create('CarConfigurationResetPage', { car: this.car, callback: (car) => this.hardResetCallback(car) });

标签: angular ionic-framework ionic2 ionic3


【解决方案1】:
 hardResetCallback = (car:Car) => {
    this.car=car;
    this.ref.detectChanges();
  }

使用粗箭头函数来防止在您的 hardResetCallback 方法范围内创建“this”。

查看更多关于箭头函数here.

相关引述:

"在经典的函数表达式中,this 关键字被绑定到 根据调用它的上下文不同的值。和 箭头函数,然而,这是词法绑定的。这意味着它 从包含箭头函数的代码中使用它。”

【讨论】:

  • 谢谢。你能解释一下为什么粗箭头或没有粗箭头会改变this 的上下文吗?
  • @CoreCreatives 设计的箭头函数不会创建自己的“this”指向的范围。这是我前段时间读到的很棒的文章:medium.freecodecamp.org/…。这里有一个很好的解释:“在经典的函数表达式中,this 关键字根据调用它的上下文绑定到不同的值。然而,对于箭头函数,this 是词法绑定的。这意味着它使用this from包含箭头函数的代码。”
【解决方案2】:

你可以使用:

this.ref.markForCheck();
if (!this.ref['destroyed']) {
    this.ref.detectChanges();
}

【讨论】:

  • 我将cd 重命名为ref,因为有问题的ref 引用了ChangeDetectorRef。考虑添加解释为什么此代码可以解决问题
猜你喜欢
  • 1970-01-01
  • 2020-07-08
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多