如何通过第二次调用来整合一个带有信息的Observable



出于教育目的,我试图调用一个检索帖子列表的服务,并且对于每个帖子,我想再次调用该服务以获取评论列表。

我使用的数据来自https://jsonplaceholder.typicode.com/posts

首先是我为这个服务提取的模型:

export interface Post {
userId: number;
id: number;
title: string;
body: string;
comments: PostComment[];
}
export interface PostComment {
postId: number;
id: number;
name: string;
email: string;
body: string;
}

这是我现在的状态。我的目标是有一个comments属性正确填充的Observable<Post>

export class PostCommentsCombination implements OnInit {
constructor(private http: HttpClient) {}
posts$?: Observable<Post[]>;
ngOnInit(): void {
this.posts$ =this.http.get<Post[]> ('https://jsonplaceholder.typicode.com/posts/').pipe(
switchMap((posts) =>
posts.map((post) =>
this.http.get<PostComment[]>(`https://jsonplaceholder.typicode.com/posts/${post.id}/comments`).pipe(
map((comments) => {
post.comments = comments;
return post;
})
)
)
)
);
}
}

但它说不能将Observable<Observable<Post>>转化为Observable<Post[]>。我不能怪他,但我不知道该怎么解决这个问题。

我会尝试这样做:

ngOnInit(): void {
const postsUrl = 'https://jsonplaceholder.typicode.com/posts/';
this.posts$ = this.http.get<Post[]>(postsUrl).pipe(
map(posts => posts.map(post =>
this.http.get<PostComment[]>(`${postsUrl}${post.id}/comments`).pipe(
map(comments => ({...post, comments}))
)
)),
switchMap(postObservables => forkJoin(postObservables))
);

}

可以将请求forkJoin发送到评论,更新post.comments字段并返回post:

this.posts$ = this.http
.get<Post[]>('https://jsonplaceholder.typicode.com/posts/')
.pipe(
switchMap(posts =>
forkJoin(
posts.map(post =>
this.http
.get<PostComment[]>(`https://jsonplaceholder.typicode.com/posts/${post.id}/comments`)
.pipe(map(comments => {
post.comments = comments;
return post;
}))
)
)
)
);

演示
posts.map((post) => ...

基本上是获取每个post并将其映射到一个Observable。你最终得到一个observable数组。你要做的是解析数组中的每个Observable来获得你想要的输出。如果您熟悉Promise,那么您需要rxjs中的Promise。所有的,本质上是forkJoin -见这个帖子承诺。所有的行为与RxJS可观察对象?

最新更新