Home > Net >  Angular Service response remembers initial parameter [duplicate]
Angular Service response remembers initial parameter [duplicate]

Time:10-02

Below a simplified version of my call to my Service.

Component:

for (let platform of this.platforms) {

    this.artistsService.getFollowers(uuid, platform)
   .subscribe((data: any[]) => { console.log(platform); })
}

Service:

  getFollowers(uuid: string, platform: string): Observable<any[]> {
    return this.http.get<any[]>(this.baseUrl   '/followers/'   platform   '/'   uuid   '?format=json', httpOptions)
      .pipe(
        catchError(this.handleError('getFollowers', []))
      );
  }

I would like the callback to remember the platform which was provided. At this moment I do not know from which platform the data is coming from.

Any ideas how a parameter can be remembered in the response?

CodePudding user response:

Instead of looping through the platforms array using for and subscribe to each item of it, you can combine them in one observable suing RxJS's from function, and then subscribe to it, where you can get every emitted platform and do some logic around it alongside its followers.

Try the following:

from(this.platforms)
  .pipe(
    concatMap((platform) =>
      this.getFollowers(uuid, platform).pipe(
        map((followers) => ({ platform, followers }))
      )
    )
  )
  .subscribe(({ platform, followers }) => {
    // Here you will get each platform and its followers.
    console.log(platform, followers);
  });

CodePudding user response:

You could use forkJoin to create a single observable that executes all requests and emits an object where the param is the key and the response is the value:

const platforms = ['one', 'two', 'three'];

const allRequests = platforms.reduce(
  (obj, p) => ({ ...obj, [p]: http(p) })
, {});

const allRequests$ = forkJoin(allRequests);

allRequests$.subscribe(
  responseObj => console.log(responseObj)
);

// Output:
//
//  {
//    one:   "response #one",
//    two:   "response #two",
//    three: "response #three"
//  }

Here's a working StackBlitz demo.

  • Related