angular - 一旦父级在 forEach 中使用 observables 完成,角度触发子函数
问题描述
在父组件中,我将可观察对象的响应推送到我传递给子组件的数组。
父组件.ts
let categoriesArr = [];
for (let category of listing.categories) {
this._projectService.getCategories().subscribe((data) => {
this.categoriesArr.push(data);
});
}
父组件.html
<child-comp #childComp [categories]="categoriesArr"></child-comp>
在子组件中,一旦可观察对象的 for 循环在父函数中完成,我想调用特定函数。
child.component.ts
@Input() public categories;
public limitCategories() {
**//I want to call this function from parent once the for loop with observables is finished**
...
}
child.component.html
<div class="Category" *ngFor="let item of categories">
...
</div>
我尝试将 categoriesArr 设为 Observable,然后在子组件中订阅它,但limitCategories()
每次有变化时我都会调用它。我只想在最后一次调用该服务后调用它一次。
解决方案
您可以使用@ViewChild
装饰器来获取子参考ChildComponent
:
父组件.ts
@ViewChild('childComp', {read: ChildComponent})
childComp: ChildComponent;
然后在循环中,您可以调用limitCategories()
方法:
for (let category of listing.categories) {
this._projectService.getCategories().subscribe((data) => {
this.categoriesArr.push(data);
this.childComp.limitCategories();
});
}
更新
如果您想等待异步操作的循环并limitCategories()
在最后一个异步操作之后触发,您可以使用async/await
等待操作完成。
父组件.ts
ngOnInit(){
this.getCategories();
}
getCategories = async () => {
for (let category of listing.categories) {
await this._projectService.getCategories().toPromise().then((data) =>
{
this.categoriesArr.push(data);
});
}
this.childComp.limitCategories();
}