In Angular 7 I am getting and posting data from an API.
GET
POST
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');
}
}
How would I post to the API without using subscribe?
You can't, you must always subscribe. If you do not care about the result you do not have to supply a callback. This is perfectly valid:
this.postService.addPost(model).subscribe();
side note: you do not need an empty pipe
in this case
See also Angular 2 http.post() is not sending the request and HttpClient - Always subscribe! documentation.
Always subscribe!
An
HttpClient
method does not begin its HTTP request until you call subscribe() on the observable returned by that method. This is true for allHttpClient
methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With