Robgit28
Robgit28

Reputation: 338

Angular2+ - Combining 2 observables calls into one

I'm trying to combine both of these calls into one so they call async or subsequently. I'm thinking I have to use of, map or switchMap.

The imageType is an enum.

It should return as a string uri.

enum

export enum ImageType {
    Avatar = 1,
    Cover = 2
}

component.ts

this.service.getphotos(ImageType.Avatar, this.id).subscribe(result => {
    this.avatarPhotos = result;
});

this.service.getphotos(ImageType.Cover, this.id).subscribe(result => {
    this.coverPhotos = result;
});

service.ts

getPhotos(imageType: ImageType, id: number): Observable<string[]> {
    return this.http.get<string[]>(`api/getphotos/${imageType}/${id}`);
    }

Upvotes: 1

Views: 74

Answers (1)

Anton Marinenko
Anton Marinenko

Reputation: 2992

Simple solution, is here:

combineLatest([
  this.service.getphotos(ImageType.Avatar, this.id).pipe(
    tap(result => (this.avatarPhotos = result)),
  ),
  this.service.getphotos(ImageType.Cover, this.id).pipe(
    tap(result => (this.coverPhotos = result)),
  )
]).subscribe()

You can do this with forkJoin either.

Upvotes: 2

Related Questions