我将对象数组共享到我的组件槽服务。所以有一次我想用新对象的属性替换数组对象的属性之一(我替换了对象)。所以我的共享对象应该在使用它的所有模板中更新。为什么替换对象不会触发Angular2中的变化检测?
https://plnkr.co/edit/0sRxSivEaEPLsNAJo7MV?p=preview
// my.component.ts
@Component({
selector: 'my-component',
template: '<div>MyComponent: {{item.name}}</div>',
})
export class MyComponent implements OnInit {
constructor(private myService: MyService) {}
private item = myService.myListData[0];
ngOnInit() {
// 1. - This triggers change detection in app.ts template
this.item.name = 'Name 1111';
setTimeout(() => {
// 2. - This doesn't trigger change detection in app.ts template
let newObj = {name: 'Name 222', age: 225};
this.item = newObj;
}, 3000);
}
}
在app.ts和my.component.ts我而言// 1个变模板的价值,但// 2触发的变化只在my.component.ts
我想知道为什么/ 2不更新app.ts模板,并有没有办法做到这一点没有循环低谷对象属性?
更新: 我设法通过使用Object.assign()解决我的问题。更换对象时没有更改检测。
setTimeout(() => {
// 2. - This doesn't trigger change detection in app.ts template
let newObj = {name: 'Name 222', age: 225};
Object.assign(this.item , newObj);
}, 3000);
相当多字幕,但几乎没有任何背景。请发布组件类,包括'@Component()'装饰器和组件模板,并解释实际行为和预期行为。 –
好吧,我认为现在没问题。谢谢 –
仍然没有HTML。 'let item'之前的'let'是多余的甚至是无效的(不是TS pro)。我认为这个变量赋值代码应该在一个方法里面。没有意义的方式,你有它。 –