为什么替换对象不会触发Angular2中的变化检测?
发布时间:2020-12-17 17:00:52 所属栏目:安全 来源:网络整理
导读:我通过服务与组件共享对象数组.所以有一刻我想用一个新对象的属性替换一个数组对象的属性(我替换对象).所以我的共享对象应该在使用它的所有模板中更新. https://plnkr.co/edit/0sRxSivEaEPLsNAJo7MV?p=preview // my.component.ts@Component({ selector: 'my
我通过服务与组件共享对象数组.所以有一刻我想用一个新对象的属性替换一个数组对象的属性(我替换对象).所以我的共享对象应该在使用它的所有模板中更新.
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模板,有没有办法在没有循环对象属性的情况下做到这一点? 更新: 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}} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |