For educative purpose, I'm trying to call a service that retrieve a list of Posts, and for each post, I would like to make a another call to this service to get the list of comments.
I'm using the data from https://jsonplaceholder.typicode.com/posts
First here are the models I extracted for this service:
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;
}
And here is my current status. My goal is to have an Observable<Post>
with the property comments
properly filled.
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;
})
)
)
)
);
}
}
But it says it cannot convert Observable<Observable<Post>>
into Observable<Post[]>
. I cannot blame him, but I'm not sure how to solve this?