Home > database >  Angular2 - Combining 2 observables calls into one
Angular2 - Combining 2 observables calls into one

Time:12-04

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}`);
    }

CodePudding user response:

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.

  • Related