简体   繁体   English

处理角度2中http.get的成功和错误响应

[英]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: 我使用foursquare api来获取搜索地点的经度和纬度坐标,函数如下所示:

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 . 我试图弄清楚如何在成功或错误的情况下执行特定任务,因此如果是成功案例,我想return coordinates如果没有向控制台输出错误,而不是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 ? 编辑:看看将来如何弹出这个问题,检查http.post成功或失败的逻辑是http.post

In fact the subscribe method allows to register callbacks for success and factures. 事实上,subscribe方法允许注册成功和制作的回调。 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. 您只能返回observable(例如来自服务)但不返回结果,因为HTTP请求是异步的。 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 蒂埃里

you can chain the http.get() with a then function, where you can put the success and error callbacks: 你可以使用then函数链接http.get() ,你可以在其中放置成功和错误回调:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM