Javascript 在有角度的2+上进行双向装订;组成部分
我有一个Ionic应用程序,其中我创建了一个组件来显示对象的一些数据。我的问题是,当我更新托管组件的父级中的数据时,组件中的数据不会更新: my-card.component.tsJavascript 在有角度的2+上进行双向装订;组成部分,javascript,angular,typescript,ionic3,angular2-components,Javascript,Angular,Typescript,Ionic3,Angular2 Components,我有一个Ionic应用程序,其中我创建了一个组件来显示对象的一些数据。我的问题是,当我更新托管组件的父级中的数据时,组件中的数据不会更新: my-card.component.ts @Component({ selector: 'my-card', templateUrl: './my-card.html' }) export class MyCard { @Input('item') public item: any; @Output() itemChange
@Component({
selector: 'my-card',
templateUrl: './my-card.html'
})
export class MyCard {
@Input('item') public item: any;
@Output() itemChange = new EventEmitter();
constructor() {
}
ngOnInit() {
// I do an ajax call here and populate more fields in the item.
this.getMoreData().subscribe(data => {
if (data.item){
this.item = data.item;
}
this.itemChange.emit(this.item);
});
}
}
my-card.html
<div class="comment-wrapper" *ngFor="let subitem of item.subitems">
{{subitem.title}}
</div>
因此,当我调用addSubItem()函数时,它不会更新组件,ngFor循环也不会显示任何内容。如果
getMoreData
方法返回一个可观察的值,则此代码需要如下所示:
ngOnInit() {
// I do an ajax call here and populate more fields in the item.
this.getMoreData().subscribe(
updatedItem => this.item = updatedItem
);
}
subscribe使异步操作执行并返回一个可观察值。当数据从异步操作返回时,它将执行提供的回调函数,并将项目分配给返回的项目。您使用
@Input()
decorator将项目声明为:
@Input('item') public item: any;
但您对其使用双向绑定:
<my-card [(item)]="item"></my-card>
如果您想使用通过
@Input()
传递的项目,将其放入卡组件中,则getMoreData()
没有意义。您的组件交互有点不正常。查看角度文档上的指南()。具体来说,使用ngOnChanges()或使用服务订阅和监视父级和子级之间的更改()。在发出api请求时,您正在破坏对象引用。您正在指定新值,即覆盖从父对象获得的输入值,并且对象不再指向同一对象,但子对象中的项
是一个完全不同的对象。由于您需要双向绑定,我们可以使用输出
:
儿童:
import { EventEmitter, Output } from '@angular/core';
// ..
@Input() item: any;
@Output() itemChange = new EventEmitter();
ngOnInit() {
// I do an ajax call here and populate more fields in the item.
this.getMoreData(item.id).subscribe(data => {
this.item = data;
// 'recreate' the object reference
this.itemChange.emit(this.item)
});
}
现在我们又有了相同的对象引用,无论您在父对象中做什么,都将反映在子对象中。我尝试删除()但仍然不起作用。另外,我只传递项目的id,卡片组件用于通过AJAX请求从服务器获取剩余的项目数据。这对我来说毫无意义,首先,你传递的是输入,而不是在子组件中使用它。您好,很抱歉,如果我的代码不太清楚,我必须去掉一些代码。基本上,我传入一个只包含I'd的item对象,然后在加载card组件时,我执行一个ajax调用来水合其余的items字段。因此,您讨论双向绑定,因此父对象需要与子对象具有相同的值(在api请求之后),或者您在父对象中所做的操作是否足以反映在子对象中。我正在考虑解决方案,所以这一点很重要:)好的,这样父对象将把id传递给子对象,子对象将从AJAX获得结果。然后,用户将与父级上创建新子项的元素交互,然后我需要在clild视图中显示该新子项。这有意义吗?您好,我已经按照您的建议更新了代码,但是当我调用addSubItem()mentod时,它仍然没有更新视图中的项目列表。我现在可以使用它,这是因为从addNewSubItem请求传回的数据不正确。谢谢
<my-card [(item)]="item"></my-card>
<my-card [item]="item"></my-card>
this.item = this.getMoreData();
import { EventEmitter, Output } from '@angular/core';
// ..
@Input() item: any;
@Output() itemChange = new EventEmitter();
ngOnInit() {
// I do an ajax call here and populate more fields in the item.
this.getMoreData(item.id).subscribe(data => {
this.item = data;
// 'recreate' the object reference
this.itemChange.emit(this.item)
});
}