Angular2+-将2个可观测调用合并为一个



我正试图将这两个调用合并为一个,以便它们调用async或后续调用。我想我必须使用、map或switchMap。

imageType是一个枚举。

它应该作为字符串uri返回。

枚举

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

组件.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;
});

服务.ts

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

简单的解决方案,在这里:

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()

您也可以使用forkJoin执行此操作。

相关内容

最新更新