Angular 2:查看未在阵列推送时更新 [英] Angular 2: View not updating on array push
问题描述
我有两个子组件.他们正在共享来自我使用 http.get/subscribe 方法加载的 json 文件的数据.出于某种原因,当我将数据推入数组时,它不会在视图中更新.不过,它会在控制台中显示更新后的数组.
I have two child components. They are sharing data from a json file that I am loading using the http.get/subscribe method. For some reason, when I push data into the array, it doesnt update in the view. It shows the updated array in the console though.
从服务加载数据的应用组件
app component loading the data from a service
this.dataService.getData()
.subscribe(
data => {
this.data = data;
},
(err) => console.log('Error: ', err),
() => console.log("success!")
);
我正在使用输入来访问我的子组件中的数据.当新值被推入数组时,Angular 2 中是否有任何方法来更新视图.
I am using inputs to access the data in my child component. Are there any ways in Angular 2 to update the view when new values are pushed into the array.
显示组件
<div *ngFor="let i of items; let k = index"><h1>{{i.title}}</h1> <p>{{i.desc}}</p></div>
按钮组件
<button (click)="addItem(i)">Add Item</button>
The Component Function
addItem(i){
let data = {title: "Some title", desc: "Some desc"};
this.data.list[i].items.push(data);
}
推荐答案
我遇到了同样的问题,我通过使用展开运算符来创建对象的新数组而不是将新元素推送到现有数组中来解决此问题.
I have the same problem and I solved this by using spread operator to create a new array of the object rather than to push new element into an existing array.
在你的情况下,我会做这样的事情:
in your case I would do something like:
addItem(i){
let data = {title: "Some title", desc: "Some desc"};
this.data.list[i].items = [...this.data.list[i].items, data];
}
这篇关于Angular 2:查看未在阵列推送时更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!