I need to get Post[] from http and then I display it on post-list component. I can delete some items on post-list template, and edit some items by navigating to another route where I use post-edit component.
How do I share same Post[] array between them so the changes will be instantly displayed in the app? I assume I need to store Post[] in the service? what is the correct way to edit/update it from component?
here I'm trying to save Post[] array inside service by tap() operator inside the service
getAllPosts(): Observable<Post[]> {
return this.http.get<Post[]>("https://jsonplaceholder.typicode.com/posts");
}
getAllUsersPosts(userId: number): Observable<Post[]> {
return this.getAllPosts().pipe(
map((posts: Post[]) => posts.filter((p: Post) => p.userId === userId)),
tap(posts => {
//storing to service
this.userPosts = posts;
})
);
}
to share the updated Post[] after delete method executed I'm trying to send stored array back to subscriber, but it doesnt help
deletePost(id: number): Observable<any> {
return this.http.delete(`https://jsonplaceholder.typicode.com/posts/${id}`).pipe(
mapTo(res => {
const index = this.userPosts.findIndex(p => p.id == id);
// console.log(index);
this.userPosts.splice(index, 1);
return this.userPosts;
})
)
}
what is the correct way to achieve this?
getAllUsersPosts,deletePostanduserPostsin your components?