Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript $http.get调用错误函数成功_Javascript_Angularjs_Angularjs Directive_Angular Promise - Fatal编程技术网

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

Javascript $http.get调用错误函数成功,javascript,angularjs,angularjs-directive,angular-promise,Javascript,Angularjs,Angularjs Directive,Angular Promise,我没有能力更改端点,如果它失败,它将返回一个200 OK响应,其中包含不同的数据。我如何让它运行error函数(promise中的第二个函数,然后是promise中的第二个函数) MyService服务: self.getData = function() { return $http.get('/api/controller/action').then(function(x) { //This will be run even on failure. How c

我没有能力更改端点,如果它失败,它将返回一个200 OK响应,其中包含不同的数据。我如何让它运行error函数(promise中的第二个函数,然后是promise中的第二个函数)

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
});

使用
$q.reject
,例如

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

您还可以检查在点击API后得到的响应状态, 这意味着API中存在一些问题

如果(状态!=200){

//做点什么


}

如果我使用拦截器,它会执行
$httpInterceptor
responseError函数吗?@JayShukla否,因为在承诺解决之前会发生这种情况。您可以非常聪明地实现拒绝来自拦截器的HTTP响应。非常感谢!