【发布时间】:2020-05-25 14:06:06
【问题描述】:
我有一个父子组件场景。在父组件中单击按钮时,我正在调用以下函数:
public goNextStep() {
this.fetchAttributes.emit(new FetchAttributesEvent("myComponent", param));//calls api and get data
this._stateService.updateStep(2); // just update step number and go to next
}
在子组件中,我对这两个都有可观察的实现,如下所示:
export class ChildComponent implements OnInit{
attributes: any[];
ngOnInit() {
this._stateService.attributesDataInjector$
.subscribe(
attributesData => {
if (attributesData != null) {
//live data
this.attributes = JSON.parse(attributesData);
}
}
)
this._stateService.stepUpdator$
.subscribe(
newStep => {
// Use this.attributes value;
}
)
}
}
现在我的问题是,由于 emit() 调用外部服务并获取数据,这需要时间,而更新步骤只是本地操作,所以它发生得很快。因此 stepUpdator$ 操作首先完成并尝试使用此时为空的 this.attributes,因为 api 调用仍在进行中。结果,我在这里得到了 undefied 的错误,并且处理继续进行。稍后,服务调用完成,attributesDataInjector$ 初始化 this.attributes。
我想以某种方式等到 this.attributes 由 attributesDataInjector$ 初始化,然后处理 stepUpdator$(类似于 promise),但我无法做到这一点。有线索吗?
【问题讨论】:
标签: observable angular-promise angular-services angular9 emit