【问题标题】:$http.get call error function from success$http.get 从成功调用错误函数
【发布时间】:2016-08-24 20:08:29
【问题描述】:

我无法更改端点,如果失败,它将返回带有不同数据的 200 OK 响应。如何让它运行错误函数(then 中的第二个函数来自承诺)?

MyService 服务:

self.getData = function() {
    return $http.get('/api/controller/action').then(function(x) {
            //This will be run even on failure. How can I call....
            return x.data;
        }, function(x) {
            //......here, from the front-end, so that, the 2nd function in
            //inside the 'then' in the controller is run.
            //This code will currently never run as it never fails server side.
            return x;
        });
};

控制器:

MyService.getData().then(function(x) {
    //Success
}, function(x) {
    //Failure
});

【问题讨论】:

    标签: javascript angularjs angularjs-directive angular-promise


    【解决方案1】:

    使用$q.reject,例如

    return $http.get('/api/controller/action').then(function(x) {
        if (x.data === 'some error condition') {
            return $q.reject(x);
        }
    

    【讨论】:

    • 如果我使用拦截器,它会执行$httpInterceptor responseError 函数吗?
    • @JayShukla 否,因为这发生在承诺解决之前。您可以实现拒绝来自拦截器的其他成功的 HTTP 响应
    • 非常聪明。非常感谢!
    【解决方案2】:

    您还可以在点击 API 后检查收到的响应状态, 比如,表示 API 有问题

    如果(状态!=200){

    // 做点什么

    }

    【讨论】:

      猜你喜欢
      • 2013-01-13
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      相关资源
      最近更新 更多