2017-01-18 28 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}} 
相关问题