我將對象數組共享到我的組件槽服務。所以有一次我想用新對象的屬性替換數組對象的屬性之一(我替換了對象)。所以我的共享對象應該在使用它的所有模板中更新。爲什麼替換對象不會觸發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)。我認爲這個變量賦值代碼應該在一個方法裏面。沒有意義的方式,你有它。 –