1

I am just starting learning angular2.I have problem while calling service in angular2.The service calls successfully,but I have problem how can I handle data. In Angular1 we do like this:

DemoService.getExchangeDataConnection().then(function(response){
//here we handle all the data
})

Angular2

constructor(private _sampleService: SampleService){
    this._sampleService = _sampleService;
}


 onClickMe(){
    this.clickMessage ='You are my hero!';
     this.error = "";
    this.countries = [];
    this._sampleService.test()
     .subscribe(
        data => this.countries = data,
        error => this.error = "Region " + this.region + " is invalid."
     );

  }

Here How can I handle data Here is My service:

export class SampleService {

constructor(http: Http){
       this.http = http;
   }

   test(){
console.log(AppSettings.API_ENDPOINT);
    return this.http.get(AppSettings.API_ENDPOINT+"oceania").toPromise()
       .then(res => console.log(res.json()), err => console.log(err));
   }

}
1
  • Don't convert you http call to promise. Commented Apr 7, 2016 at 11:22

1 Answer 1

4

If the test method returns an observable you need to subscribe on it in a similar way than with promises:

this._sampleService.test()
   .subscribe(
     data => this.countries = data,
     error => this.error = "Region " + this.region + " is invalid."
   );

For example for a test method like this:

test() {
  return this.http.get('http://...').map(res => res.json());
}

You can notice that you can also use promises with Angular2. In this case, you will handle the response the same way as you did.

Edit

You could update your test method this way:

test(){
  console.log(AppSettings.API_ENDPOINT);
  return this.http.get(AppSettings.API_ENDPOINT+"oceania")
               .map(res => console.log(res.json());
 }

and call it like this:

this.service.test().subscribe(data => {
  (...)
});

If you want to leverage promise, you need to return something into your then callback to leverage chaining:

test(){
  console.log(AppSettings.API_ENDPOINT);
  return this.http.get(AppSettings.API_ENDPOINT+"oceania").toPromise()
    .then(res => res.json(), err => console.log(err)); // <---------
}

You can get your data now this way:

this.service.test().then(data => {
  (...)
});
Sign up to request clarification or add additional context in comments.

4 Comments

I got subscribe is not a function
What does the test method return?
this returns the data,but I don't know how can I handle this
Could add the content of this method in your question? It will be easier to help you...

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.