Moshe
Moshe

Reputation: 2684

Angular Subscription called twice

I have a chain of observables which follow this logic: getStyles() --> getPrices()

For every config.id in configs, getStyles() returns a style Object, this style Object is passed to getLease where a price is appended to it and is then pushed an array called "style"

  getStyles(configs: any) {
      configs.forEach(config => {
           this._APIService.getStyleByID(config.id).subscribe(
                res => {
                    res.config = config;
                    this.getLease(res);
                }
           );
    });

  }

  getLease(style: any): void {
      this._priceService.getPrice().subscribe(
        price => {
            style.price = price;
            this.garage.push(style);
            console.log(this.garage);
        });
  }


}

The issue I am experiencing is that there is a duplicate call being made because the style array has 2x as many style objects as it needs to have. The issue being that Angular is calling this._APIService.getStyleByID() twice when I expect it to call once. How do I fix my Observables to only be called once?

Upvotes: 2

Views: 1607

Answers (1)

Yeysides
Yeysides

Reputation: 1292

Try switchMap, it's like mergeMap but it cancels the last request if it changes:

  getStylesWithoutYear(): void {
    this._APIService.getStylesWithoutYear()
      .switchMap(styles => {
         styles.years.forEach(year => {
          year.styles.forEach(style => {
              this._APIService.getStyleByID(style.id)
           })
         })
      })
      .subscribe(style => {
        console.log('style', style)
      })
  }

Upvotes: 1

Related Questions