1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.