How to make an HTTP POST request in Angular2 and print the response

I am new to Angular2 and am creating a sample project to learn it. I am aware of how to make HTTP calls in Angular2 and found this example code snippet:

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'm not sure what the subscription does, but my main goal is to print the answer. From this code, I see the answer, but I'm not sure how to "isolate and access it" (I hope this makes sense). My question is how to print the answer to the console?

+4
source share
1 answer

My question is how to print the answer to the console?

You can simply type res:

.subscribe((res:Person) => { this.postResponse = res; console.log(res); });

Click here for a demo panel .


I'm not sure what to sign (...)

Http.post(...) () Observable<Response> ().

POST (a Observable<Response>) .map() (link). , JSON :

.map((res: Response) => res.json())

.map() Observable<Response>. subscribe.

subscribe() (link) Observable (link), , , "" "" , / ( "" ), , - () next, (on) error (on) complete.

, .subscribe() :

.subscribe(
     (response) => {
            /* this function is executed every time there a new output */
           console.log("VALUE RECEIVED: "+response);
     },
     (err) => {
            /* this function is executed when there an ERROR */
            console.log("ERROR: "+err);
     },
     () => {
            /* this function is executed when the observable ends (completes) its stream */
            console.log("COMPLETED");
     }
 );

, Angular2 Http, RxJS Observables. , , ( :).

+9

All Articles