6

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 ?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Mohit Bumb
  • 2,466
  • 5
  • 33
  • 52

2 Answers2

2

You can using Observables in angular . and please checkout this below discussion

What is the difference between Promises and Observables?


Now try this below code instead of your code in component

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

and you service code should be

fetchData(url,request)
  {
    return this.http.post(this.apiUrl+url,request).map(
        (response) => {return response.json()}
    );
  }
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
2

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

    }
Michael Filler
  • 328
  • 2
  • 12