Angular2变化检测“检查后表达已变化". [英] Angular2 change detection "Expression has changed after it was checked"

查看:61
本文介绍了Angular2变化检测“检查后表达已变化".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular2(最终版)中遇到一个问题,即更改检测和组件之间的数据流.我已经解决了这个问题,但对我来说似乎有点不客气 所以想知道是否有更好的方法.

I have an issue in Angular2 (final) around change detection and data flow between components. I have worked around it but it seems a little hacky to me so was wondering if there is a better way of doing it.

基本上,我有一个具有子组件B的组件A,还有* ngFor可以创建多个子组件C.

Basically I have a component A that has a child component B and also *ngFor that creates number of children components C.

对于每个组件C,在父组件A中为每个C实例定义一个@ Output.基于该输出,确定组件A的另一个属性(仅是一个数字),并且使用在组件B上为@Input.

For every component C, there is an @Output defined that is handled in the parent component A for each instance of C. Based on that output, another property on component A is determined (just a number) and thats used as @Input on component B.

在DEV模式下,每次触发组件C中的@Output时,控制台中都会出现以下错误:

In DEV mode, every time the @Output in components C is triggered, I am getting below error in the console:

Expression has changed after it was checked. Previous value: XX. Current value: XX.

从对它的了解中可以看出,由于Angular2中的单向数据流,它的期望值很高.我想知道如何使其在我的方案中正常工作吗?

From reading about it, its kind of expected due to uni-directional data flow in Angular2. I wonder how to make it work properly in my scenario?

我将ChangeDetectorRef临时注入到组件A中,并在处理C实例的@Output事件的函数中调用其detectChanges()方法. 我担心它不是很有效.我可能会尝试对其进行改进,并仅在最后一项事件(所有C组件同时发送该事件)之后才调用它,但是随后,我将担心事件的异步性质和某些意外行为.

I temporarily injected ChangeDetectorRef in component A and call its detectChanges() method in the function that handles @Output event from instance of C. I am worried that its not very efficient tho. I could probably try improve it and call it only after the last item's event (all the C components send that event at the same time) but then I would be worried about async nature of the events and some unexpected behaviors.

有人知道如何克服这个问题吗?就组件之间的数据流而言,我的设计是否存在根本缺陷? 我应该选择共享服务之类的东西来交换数据吗?

Does anyone have an idea how to overcome this problem? Is my design fundamentally flawed in terms of the data flow between the components? Should I go for something like a shared service instead to exchange data?

非常感谢您的帮助.

推荐答案

您可以注入private cdRef:ChangeDetectorRef并在ngOnChanges()的末尾调用this.cdRef.detectChanges().这样,Angular再次运行更改检测,并且不会抱怨以前修改过的模型值.

You can inject private cdRef:ChangeDetectorRef and call this.cdRef.detectChanges() at the end of ngOnChanges(). This way Angular runs change detection again and won't complain about previously modified model values.

class MyComponent {
  constructor(private cdRef:ChangeDetectorRef) {}

  ngOnChanges(changes) {
    this.xxx = ...
    ...
    this.cdRef.detectChanges();
  }
}

这篇关于Angular2变化检测“检查后表达已变化".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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