Home > database >  How to use MergeMap in Angular 11 / ionic 6?
How to use MergeMap in Angular 11 / ionic 6?

Time:04-04

I am very new with the MergeMap method to combine multiple API requests. I have following and reading this tutorial how to do it.

https://levelup.gitconnected.com/handle-multiple-api-requests-in-angular-using-mergemap-and-forkjoin-to-avoid-nested-subscriptions-a20fb5040d0c

This is my code to get data from an API:

Service.ts

getPriceList(): Observable<Price[]> {    
    this.http.get<Price[]>(this.baseUrl).pipe(     
      map( priceId => {
        const id = priceId[0];
        this.priceId = id.id;
        return id;
            }),
     mergeMap( Id=> this.http.get(this.baseUrl2   /${Id.id})),
      
    ).subscribe( productPrices => {
       this.productPrices = productPrices;
    });
  }

I need all the data from the first baseUrl, but I assign the Id to use it in my second api request. I call this method in home.ts like this:

 this.dataService.getPriceList().subscribe(response => {
      console.log(response);
      this.priceListData = response;  

There is no error when I call this method in the file.

The error is in the method from Service.ts

A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)

I am using the return statement in the first api request.

I have tried this solution:

A function whose declared type is neither 'void' nor 'any' must return a value

Then I get the following error:

Type 'Subscription' is missing the following properties from type 'Observable<Crypto[]>': _isScalar, source, operator, lift, and 6 more.ts(2740)

How to use the MergeMap the right way in Angular 11 / ionic 6?

CodePudding user response:

I think you should return something on getPriceList, which you weren't, and if you subscribe inside getPriceList there is no observable anymore to subscribe after that

  getPriceList(): Observable<Price[]> {
    return this.http
      .get<Price[]>(this.baseUrl)
      .pipe(
        map(priceId => {
          const id = priceId[0];
          this.priceId = id.id;
          return id;
        }),
        mergeMap(id => this.http.get(`this.baseUrl2${id.id}`))
      )
  }

and the call

this.dataService.getPriceList().subscribe(response => {
  console.log(response);
  this.priceListData = response;  
});
  • Related