abhilash reddy
abhilash reddy

Reputation: 1586

How to use observables in angular2 service calls?

I have a service call from my component which gets the list of heroes.from that function where it calls another function which has the http request...How can i subscribe to the function call so that i will get the response properly...Here is my plunker demo http://plnkr.co/edit/UM9STMwaOsgolhBjADjx?p=preview ... This is how i am calling the service from my component

 ngOnInit() { 
              this.heroService.getHeroes()
                 .subscribe(
                  heroes => this.heroes = heroes,
                  error =>  this.errorMessage = <any>error);
 }

And in my Service class i have called this method which calls another method which has http request and subscribed to that...

  getHeroes (){
return this.GetListOfHeroes()
        .subscribe((data: any) => {
            return data;
        }
        );
}

And finally this is the method which gets the list...

  GetListOfHeroes(){
    return this.http.get(this.heroesUrl)
                .map(this.extractData)
                .catch(this.handleError);
 }

If i directly call GetListOfHeroes() method from my component it works fine but if i try to call that from another method it shows this error this.heroService.getHeroes(...).subscribe is not a function Somebody please tell me where i am doing wrong...Thanks

Upvotes: 1

Views: 657

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657078

Use .map(...) instead of .subscribe(...) in getHeroes() like:

  getHeroes (){
    return this.GetListOfHeroes()
    .map((data: any) => {
        return data;
    });
  }

This way getHeroes() returns an Observable while with .subscribe() it returns a Subscription you can't subscribe to.

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202138

In fact, you should subscribe within the getHeroes method since it will return a subscription and not an observable.

getHeroes (){
  return this.GetListOfHeroes()
    .subscribe((data: any) => { // <-----
        return data;
    });
}

The subscribe method can only be called on an observable. The subscription object is usable to cancel the subscription...

In fact, it depends on what you want to do within the getHeroes method. You can, for example, leverage the do operator or the map one. Here is a sample:

getHeroes (){
  return this.GetListOfHeroes()
    .do((data: any) => { // <-----
      // do something with data
    })
    .map((data: any) => {
      // return something else in the data flow
      return { attr: 'value' };
    });
}

Upvotes: 1

Related Questions