$ http.get成功调用错误函数

时间:2016-08-23 04:07:52

标签: javascript angularjs angularjs-directive angular-promise

我无法更改端点,如果失败,它将返回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
});

2 个答案:

答案 0 :(得分:7)

使用$q.reject,例如

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

答案 1 :(得分:0)

您还可以检查您在点击API后获得的响应状态, 比如,表示API中存在一些问题

如果(状态!= 200){

//做点什么

}