-2

I have this function that I want to run. The problem is that it doesn't wait for the two calls to finish and instantiate rule1 and rule2 so I get error that rule1.optionhead is undefined. I have tried to have the code nested to each subscribe but then the create execution happens more times than I want. What can I do to fix it?

To clarify, I use this for loop because the selectedScenario is an array of IDs which are in an input form 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));
    }

  }
}
Antifa
  • 377
  • 1
  • 4
  • 14

2 Answers2

1

Try 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

    }
    );
Indrakumara
  • 1,595
  • 17
  • 22
-2

You should use this code for that

removeAll() {
  Promise.all([
    this.storage.remove(key1),
    this.storage.remove(key2),
    this.storage.remove(key3),
  ]).then(value => doSomething());
  • 2
    If you are going to post and answer, you should make it relevant to the OP. What you have posted here doesn't seem to have anything to do with what was asked above. Nor does it have any explanation of what you are solving with this code. – R. Richards Sep 22 '18 at 13:57