angular - Ionic、Angular - ChangeDetectorRef 未定义

标签 angular ionic-framework ionic2 ionic3

我正在像这样导入 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 = (car:Car) => {
    this.car=car;
    this.ref.detectChanges();
  }

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

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

相关引用:

"In classic function expressions, the this keyword is bound to different values based on the context in which it is called. With arrow functions however, this is lexically bound. It means that it uses this from the code that contains the arrow function."

关于angular - Ionic、Angular - ChangeDetectorRef 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51418124/

相关文章:

css - Snackbar 动态颜色变化 Angular 7

Android 项目未解析任何静态 Assets

android - 您可以使用 native 应用程序做什么,而您不能使用混合应用程序

css - 如何更改 ionic 2 中 ion-header 的背景颜色?

javascript - Ionic 2 上的 NavPush 中包含对象时出现间歇性错误

javascript - 无法呈现在运行时动态设置的集合

typescript - Angular2 - Iterable Differ 不检测变化

ionic2 - ionic 2选择: remove selected option

node.js - 为什么我不能使用 "ng new"语法创建新项目

javascript - 访问 ionic 项目中自定义 cordova 插件的项目资源