Angular2+ - 将 2 个 observables 调用合并为一个
Angular2+ - Combining 2 observables calls into one
我正在尝试将这两个调用合并为一个,以便它们调用异步或后续调用。我在想我必须使用 map 或 switchMap。
图像类型是一个枚举。
它应该 return 作为字符串 uri。
枚举
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}`);
}
简单的解决方案,在这里:
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
执行此操作。
我正在尝试将这两个调用合并为一个,以便它们调用异步或后续调用。我在想我必须使用 map 或 switchMap。
图像类型是一个枚举。
它应该 return 作为字符串 uri。
枚举
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}`);
}
简单的解决方案,在这里:
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
执行此操作。