【发布时间】:2022-01-16 07:55:40
【问题描述】:
type Movie = {id: string};
type FullMovie = {id: string, picture: string};
我有一个返回 Movie 类型数组的 url:
http.get(url).subscribe(res: Movie[])
我将http.get(movie.id) 用于数组中的每个 电影,返回FullMovie:
http.get(movie.id).subscribe(res: FullMovie)
所以本质上我想创建一个返回 FullMovie 对象流的方法,因为请求解析:getAll = (url): Observable<FullMovie>
getAll = (url): Observable<FullMovie> => {
return http.get(url)
//must pipe the array into a stream of FullMovies but not a stream of FullMovie Observables. I don't want to subscribe to each of the returned FullMovies
//something like
.pipe(//map(array => array.forEach(movie => return http.get(movie.id))))
}
目前我有以下可行的解决方案,但我想要一个更简洁的解决方案:
private getFull = (queryGroup: string): Observable<TMDBMovie> =>
new Observable<TMDBMovie>((observer) => {
//get movie array
this.httpGet(queryGroup).subscribe((movies) => {
var j = 0;
if (movies.length === 0) return observer.complete();
//loop through elements
movies.forEach(movie => {
this.getById(movie.id).subscribe(
(res) => complete(observer.next(res)),
(error) => complete()
);
});
}
const complete = (arg: any = 0) => {
if (++j === len) observer.complete();
};
});
});
编辑:
这行得通
newGetFull = (queryGroup: string) =>
this.httpGet(queryGroup)
.pipe(concatMap((arr) => from(arr)))
.pipe(
mergeMap((movie) => this.getById(movie.id).pipe(catchError(() => of())))
);
【问题讨论】:
标签: javascript rxjs observable rxjs-pipeable-operators