Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return data coming from response instead of subscription json in Angular 2/4

Tags:

My Service :

fetchData(url,request)
  {
    return this.http.post(this.apiUrl+url,request).subscribe(
        (response) => {return response.json()}
    );
  }

My Component :

ngOnInit()
    {
        this.response = this.dataService.fetchData('friends/grow_network',{});
        console.log('s ',this.response);
    }

if I console response.json() in service it shows proper data which is coming from api but if I console in component it shows like this :

Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null…}

how to get data in component which is coming from api not Subscriber data ?

like image 483
Mohit Bumb Avatar asked Jul 27 '17 06:07

Mohit Bumb


1 Answers

When doing it your way, you write in the variable "reponse" the observable object and not the result. The value of the result is not there yet when calling the method, because it will be asynchronous.

To get what you want you have to do the following:

fetchData(url,request)
  {
    return this.http.post(this.apiUrl+url,request).map(
        (response) => {return response.json()}
    );
  }

ngOnInit()
    {
        this.response = this.dataService.fetchData('friends/grow_network',{})
                         .subscribe(result => {
                           this.response = result;
                           console.log('s ',this.response);
                         });

    }
like image 117
Michael Filler Avatar answered Sep 25 '22 00:09

Michael Filler