为什么替换对象不会触发Angular2中的变化检测?

前端之家收集整理的这篇文章主要介绍了为什么替换对象不会触发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);
  }
}

在我的情况下// 1在app.ts和my.component.ts中更改模板值但是// 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);

解决方法

我认为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}}

猜你在找的Angularjs相关文章