最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Handling success and error responses from http.get in angular 2 - Stack Overflow

programmeradmin1浏览0评论

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 (mented 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 ?

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 (mented 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 ?

Share Improve this question edited Jan 15, 2016 at 2:31 Mark Rajcok 365k114 gold badges500 silver badges494 bronze badges asked Jan 14, 2016 at 9:25 IljaIlja 46.6k103 gold badges289 silver badges528 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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 ponents for example and set ponent attributes to be displayed in the view.

Hope it helps you. Thierry

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
});
发布评论

评论列表(0)

  1. 暂无评论