I am new to Angular2 and buuilding a sample project to learn it. I am curently looking at how to make HTTP calls in Angular2 and found this code snippet example:
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://www.syntaxsuccess.com/poc-post/',
JSON.stringify({firstName:'Joe',lastName:'Smith'}),
{headers:headers})
.map((res: Response) => res.json())
.subscribe((res:Person) => this.postResponse = res);
I am not sure what the subscribe does, but my main objective is to print the response. From this code I can see the response, but I am unsure how to "isolate and access it" (I hope that makes sense). My question is how would I print the response to the console?
My question is how would I print the response to the console?
You can just print res
:
.subscribe((res:Person) => { this.postResponse = res; console.log(res); });
Click here for demo plunk.
I am not sure what the subscribe does (...)
The result of Http.post(...)
(link) is an Observable<Response>
(link).
In your code, you pick the result of the POST (an Observable<Response>
) and call .map()
(link) on it. In your case, you do that to parses the response as JSON and transform it into an object:
.map((res: Response) => res.json())
Now, the result of .map()
is also an Observable<Response>
. That's when you call subscribe
.
subscribe()
(link) is a method of the Observable
(link) class, and it allow you to, tipically, "register" or "subscribe" three functions that will handle/read the results (or "events") this observable emits - they are called (on)next
, (on)error
and (on)complete
.
So, the code using .subscribe()
is usually:
.subscribe(
(response) => {
/* this function is executed every time there's a new output */
console.log("VALUE RECEIVED: "+response);
},
(err) => {
/* this function is executed when there's an ERROR */
console.log("ERROR: "+err);
},
() => {
/* this function is executed when the observable ends (completes) its stream */
console.log("COMPLETED");
}
);
So, in order to fully understand Angular2's Http, I suggest you read some resources on RxJS and Observables. When you get back from it, things will be much simpler, I promise (no pun intended :).
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