Angular http post to return data back through service to component

user6321478 picture user6321478 · Sep 12, 2017 · Viewed 15.4k times · Source

I Want to return data (@@identity) from sql server through the service to the component

The Web api is definitely being called and sending data back.

However, since I am new to Angular 2/4 ( i was used to angular 1 ) i would normally just do return on a service , and set a variable or object to the caller.

Currently this is what I am doing

Component

this.trackerFormService.addSession();  // CURRENT

but since the value is a single id, like 5, shouldn't i create something in typescript to retrieve it?

this.myId = this.trackerFormService.addSession();    // ???

Then in the Service

private _url = 'http://localhost:60696/api/tracker';

addSession() { 
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    this.http.post(this._url, JSON.stringify({}), options).catch(this.handleError).subscribe();

}

Now for the above to pass the ID from the service (addSession() method back to component, shouldn't i do a return ?

return this.http.post(this._url, JSON.stringify({}), options).catch(this.handleError).subscribe();

but will that truly even work?

Web api (.net core ) looks like this

return Created($"api/sessiontrackers/{sessionTracker.Id}", sessionTracker);

Answer

Dheeraj Kumar picture Dheeraj Kumar · Sep 12, 2017

This will surely help you with making post call to web api

https://dheerajsroy.wixsite.com/dheerajkumar/single-post/2017/09/07/How-to-make-Post-Call-in-Angular-2

In your service

 return this.http.post(Url, JSON.stringify(data), requestOptions)
              .map((response: Response) => response.json())

In your Component

this.service.addSession(this.data).subscribe(
      data => { console.log(data) // Data which is returned by call
      },
      error => { console.log(error); // Error if any
      },
      ()=> // Here call is completed. If you wish to do something 
      // after call is completed(since this is an asynchronous call), this is the right place to do. ex: call another function
    )