Ilja
Ilja

Reputation: 46479

Handling success and error responses from http.get in angular 2

I am using foursquare api to grab longitude and latitude coordinates for searched venue, function looks like this:

getCoordinates(params) {
   this.http.get(URL+params)
    .map(res => res.json())
    .subscribe(
      data => this.coordinates = data,
      err => this.logError(err)
    );
   // return coordinates;
  }

I am trying to figure out how to perform specific tasks in case of success or error, so if it is a success case I want to return coordinates if not print an error to the console, but not return coordinates. I think I more or less got the error bit down, but can't figure success action (commented it out at the moment as it is called in success and error cases)

EDIT: seeing how this question can pop up in the future, what would be logic to check for success or failure of a http.post ?

Upvotes: 4

Views: 5335

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202176

In fact the subscribe method allows to register callbacks for success and factures. Perhaps arrow functions disturb you a bit:

this.http.get(...)
  .map(res => res.json())
  .subscribe(
    data => {
      // Processing for successfull response
    },
    error => {
      // Processing for failures
    }
  );

You can only return the observable (for example from a service) but not a result because HTTP requests are asynchronous. Then you can subscribe on it within components for example and set component attributes to be displayed in the view.

Hope it helps you. Thierry

Upvotes: 4

devqon
devqon

Reputation: 13997

you can chain the http.get() with a then function, where you can put the success and error callbacks:

this.http.get(URL+params).then(function(data){
    // success
}, function(data){
    // error
});

Upvotes: 0

Related Questions