Shubham Kumar Shubham Kumar - 3 months ago 32
HTTP Question

how to return the data after getting response in http api call in angular 4?

This is my function which i define in my service and i am calling this
service method in my component but it return before the response has
come from http api call, so i get undefined return data.

.post("http://localhost:3000/home", {
email: JSON.parse(this.cookieService.get("token")).email
.subscribe(data => {
this.result = JSON.parse(data["_body"]);
send=>{return this.result}

Answer Source

Return the observable from your service like the following,

home() : Observable<any> { 
    return this._http
      .post("http://localhost:3000/home", {
          email: JSON.parse(this.cookieService.get("token")).email
     .map(data => {
        let result = JSON.parse(data["_body"]);
        return result;

And subscribe on the returned Observable from you component code like this,

this.chatService.home().subscribe((result) => { this.result = result; });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download