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

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( ',this.response);
    }

      

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

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

      

how to get data in component that comes from api and not subscriber data?

+3


source to share


2 answers


When you do it your way, you are writing the observable in the response variable, not the result. The result value does not yet exist when the method is called because it will be asynchronous.

To get what you want, you need 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( ',this.response);
                         });

    }

      

+1


source


You can use Observables in angular. and please check this below discussion

Angular - Promise vs Observable


Now try this below code instead of code in component



 this.response = this.dataService.fetchData ('friends/grow_network'{})
                 .subscribe(res=> { console.log(res);
                 }), error => alert(error);

      

and the service code should be

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

      

+2


source







All Articles