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

How to wait in Angular for two calls to finish

我有我想要的这个功能运行。问题是它不等待两个调用完成并实例化 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));
    }

  }
}

你应该为此使用此代码

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

尝试 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

    }
    );