2017-01-18 71 views
2

我將對象數組共享到我的組件槽服務。所以有一次我想用新對象的屬性替換數組對象的屬性之一(我替換了對象)。所以我的共享對象應該在使用它的所有模板中更新。爲什麼替換對象不會觸發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); 
+3

相當多字幕,但幾乎沒有任何背景。請發佈組件類,包括'@Component()'裝飾器和組件模板,並解釋實際行爲和預期行爲。 –

+0

好吧,我認爲現在沒問題。謝謝 –

+1

仍然沒有HTML。 'let item'之前的'let'是多餘的甚至是無效的(不是TS pro)。我認爲這個變量賦值代碼應該在一個方法裏面。沒有意義的方式,你有它。 –

回答

0

我想OP是想要將幾個視圖綁定到相同的服務數據。 這裏是一個plunker(修改後的海報原件),顯示如何完成它。基本上將視圖綁定到相同的服務成員,而不是組件的個人成員。因此這些更改會自動反映在所有類似的綁定中。

https://plnkr.co/edit/PNQmLarmP3g7j7f42cXD?p=preview

@Component({ 
    selector: 'my-component', 
    template: '<div>MyComponent: {{myService.Item.name}}</div>', 
}) 
export class MyComponent implements OnInit { 
    constructor(private myService: MyService) {} 

    private item = myService.myListData[0]; 

    ngOnInit() { 
    // 1. - This triggers change detection 
    this.item.name = 'Name 1111' 
    this.myService.Item = this.item; 

    setTimeout(() => { 
     // 2. - This doesn't trigger change detection in app.ts template 
     let newObj = {name: 'Name 222', age: 225}; 
     this.myService.Item = newObj; 
    }, 3000); 
    } 
} 

關於這個話題,我如果有一種方法來達到同樣的創造像一個速記服務成員的引用在組件的HTML中使用一直在想。

Item = Alias of MyService.Item ; 

和HTML只會綁定到

{{Item}} 
相關問題