离子,角度-ChangeDetectorRef未定义

gfe*_*els 4 ionic-framework ionic2 ionic3 angular

我像这样导入ChangeDetectorRef:

import { Component, ViewChild, ChangeDetectorRef , ElementRef } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)

并在我的页面的构造函数中初始化更改检测器,如下所示:

constructor(
    ...
    private ref: ChangeDetectorRef
  )
Run Code Online (Sandbox Code Playgroud)

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

 hardResetCallback(car:Car){
    this.car=car;
    this.ref.detectChanges();
  }
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

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

然后这就是我在模态中得到它的方式:

 this.callback=this.navParams.get('callback');
Run Code Online (Sandbox Code Playgroud)

我像这样在AJAX调用的成功方法中从模式调用回调:

this.callback(response);
Run Code Online (Sandbox Code Playgroud)

Ser*_*nko 7

 hardResetCallback = (car:Car) => {
    this.car=car;
    this.ref.detectChanges();
  }
Run Code Online (Sandbox Code Playgroud)

使用粗箭头功能可以防止在hardResetCallback方法范围内创建“ this”。

在此处查看有关箭头功能的更多信息

相关报价:

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

  • @CoreCreatives 箭头函数的设计不会创建自己的“this”指向的范围。这是我前段时间读到的很棒的文章:https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26。这里有一句很好地解释了它的引用:“在经典的函数表达式中,this 关键字根据调用它的上下文绑定到不同的值。然而,对于箭头函数,this 是词法绑定的。这意味着它使用 this from包含箭头函数的代码。” (2认同)