简体   繁体   中英

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

Simple solution, is here:

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

You can do this with forkJoin either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM