In Angular 7 I am getting and posting data from an API.
GET
- To get data I am using an Observable (posts$) and pipe / map;
- I am using async in the Component HTML and not using Subscribe;
- This is the approach I have seen recently including in Angular docs.
POST
- The Service Post method also returns data:
Possible validation errors or the ID of the created Post.
I need to get any of them when they are returned by the API.
However, when calling the service to POST the following does nothing:
this.postService.addPost(model).pipe();
Unless I use subscribe
as follows:
this.postService.addPost(model).pipe().subscribe();
Question How would I post to the API without using subscribe? And does it make sense?
Component
export class PostComponent implements OnInit {
posts$: Observable<GetPostsModel[]>;
constructor(private postService: PostService) { }
ngOnInit() {
this.posts$ = this.getPosts();
}
addPost(model: AddPostModel) {
this.postService.addPost(model).pipe().subscribe();
}
getPosts(): Observable<GetPostsModel[]> {
return this.postService.getPosts().pipe(
map((response: GetPostsResponse) =>
return {
// Map Response to GetPostsModel here
};
}));
}
}
Service
export class PostService {
constructor(private httpClient: HttpClient) { }
public addPost(model: AddPostModel): Observable<AddPostResponse>> {
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
return this.httpClient.post<AddPostResponse>>('posts', model, { headers: headers });
}
public getPosts(): Observable<GetPostsResponse>> {
return this.httpClient.get<GetPostsResponse>>('posts');
}
}