Last week a colleague asked me for help because his HTTP POST method was not invoked inside his Angular 2 service.
Here is the code he was using:
this.http.post(this.apiUrl, JSON.stringify(user), this.getRequestOptions());
So why does this code doesn’t work?
Reason is that the post
method of the Http
class returns a cold observable. Cold observables only are invoked when someone subscribes to it. They are kind of ‘lazy’. As we didn’t subscribe for the Observable results nothing happens. Here is a fix:
this.http.post(this.apiUrl, JSON.stringify(user), this.getRequestOptions()).subscribe(r=> {});
More information about cold vs hot observables can be found here: https://medium.com/@benlesh/hot-vs-cold-observables-f8094ed53339#.an6vzfics