如何在 Angular 中等待两个调用完成



我有这个函数要运行。问题是它不会等待两个调用完成并实例化rule1rule2所以我得到的错误rule1.optionhead is undefined.我试图将代码嵌套到每个subscribe但是创建执行的次数比我想要的要多。我能做些什么来修复它?

澄清一下, 我使用它 for 循环,因为selectedScenario是一个 ID 数组,它们以输入形式ngValue

saveFunction() {
for (const pair of this.selectedScenario) {
this.ruleToSave = null;
this.ruleService.find(pair[0]).subscribe((ruleResponse: HttpResponse < Rule > ) => {
this.rule1 = ruleResponse.body;
});
this.ruleService.find(pair[1]).subscribe((ruleResponse: HttpResponse < Rule > ) => {
this.rule2 = ruleResponse.body;
});
const head1 = this.rule1.optionHead;
const head2 = this.rule2.optionHead;
if (
this.selectedOption === head1 &&
this.selectedOption !== head2 &&
(this.selectedWeakerOption === '' || head2 === this.selectedWeakerOption)
) {
..some code
this.subscribeToSaveResponse(this.ruleService.createRule(this.ruleToSave));
}
}
}

尝试 forkJoin

Observable.forkJoin([
this.ruleService.find(pair[0]),
this.ruleService.find(pair[1])])
.subscribe(
(result: any[]) =>{ 
this.rule1 = result[0]; 
this.rule1 = result[1]; 
..Your code
}
);

你应该用这段代码来做

removeAll() {
Promise.all([
this.storage.remove(key1),
this.storage.remove(key2),
this.storage.remove(key3),
]).then(value => doSomething());

最新更新