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

时间:2018-09-22 13:43:22

标签: angular typescript subscribe

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

  }
}

2 个答案:

答案 0 :(得分:1)

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

    }
    );

答案 1 :(得分:-2)

您应该为此使用该代码

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