Angular http post to return data back through service to component

17,816

Solution 1

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
    )

Solution 2

You can return the Observable from your addSession, without .subscribe

addSession() { 
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

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

And because this is an asynchronous call, subscribe to your observable in your component and when it will finish the call, assign the value to your myId.

this.trackerFormService.addSession().subscribe(result => this.myId = result);
Share:
17,816
Admin
Author by

Admin

Updated on June 16, 2022

Comments

  • Admin
    Admin almost 2 years

    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);