变更检测未注册数据变更 [英] Change detection not registering data changes

查看:63
本文介绍了变更检测未注册数据变更的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html结构,在组件内部有一个组件(为此忘记了合适的词).

I have an html structure with a component inside a component (forgot the proper word for it).

基本上是这样工作的(大大简化了):

working basicly like this (largely simplified):

主要html:

<div *ngFor="let item of data">
  <app-item [item]="item"></app-item>
</div>

<button (click)="addItem()">Add</button>

项目html:

<div>{{item.name}}</div>

<button (click)="deleteItem()">Delete</button>

在应用程序项内的

中,我显示了列表中的几项.该列表通过http.get请求直接从数据库中获取数据.

inside the app-item I display several items out of a list. The list gets it's data straight out of the database via an http.get request.

现在,我还具有添加或删除两个都可以工作的项目的功能(分别将项目添加到数据库中或从数据库中删除项目都很好).尽管更改检测未获取任何更改,并且需要刷新站点(例如,通过F5)以显示更改.

Now I also have functionality to add or delete items which both work (items get added or removed respectively to or from the database just fine). Though the change detection does not pick any of it up and the site needs to be refreshed (via F5 for example) to display the changes.

我检查了代码(并非全部来自我),找不到任何指定的变更检测策略.

I checked the code (not all of it is from me) and couldn't find any specified change detection strategie.

我还尝试通过ChangeDetectorRef(this.ref.detectChanges();)从添加和删除功能中手动进行tigger更改检测. 尽管这也没有消除手动刷新页面以查看更改的需要.

I also tried to manually tigger change detection from the add and delete function via the ChangeDetectorRef (this.ref.detectChanges();). Though that also did not take away the need to manually refresh the page to see the changes.

现在我缺少什么来进行变更检测?或者,如何在添加/删除方法中手动触发它?

Now what am I missing for change detection to pick this up? Or alternatively, how can I manually trigger it within my add/delete methods?

推荐答案

由于要在现有数组中添加或删除元素,所以angular无法选择更改.

Since you are adding or deleting element in existing array angular is not able to pick the changes.

为此,您可以喜欢

  • 使用与items= items.slice();
  • 相同的数组元素的新对象分配数组引用
  • 或者您可以将Object.assign方法用作items= Object.assign([],items);
  • 这两项都应该在对数组进行更改之后完成.
  • assign array reference with new object of same elements of array as items= items.slice();
  • Or you can use Object.assign method as items= Object.assign([],items);
  • Both the things should be done after making changes to the array.

要手动触发更改检测,您可以在此链接上按照答案

To manually fire change detection you can follow answer on this link

在组件中注入ChangeDetectorRef,然后使用该对象的detectChanges()方法手动触发更改检测.

Inject ChangeDetectorRef in your component and then use detectChanges() method of that object to fire change detection manually.

constructure(private cd: ChangeDetectorRef) {}

someMethod() {
    this.cd.detectChanges();
}

这篇关于变更检测未注册数据变更的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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