变更检测未注册数据变更

编程入门 行业动态 更新时间:2024-10-25 22:34:42
本文介绍了变更检测未注册数据变更的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个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(); }

更多推荐

变更检测未注册数据变更

本文发布于:2023-08-01 08:56:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267032.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未注册   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!