2013-01-23 118 views
1

我有一个问题与angularjs应用程序与REST API通信。问题是api返回一个状态码,并且还添加了一个状态描述,如HTTP/1.1 417 Invalid quantity。 使用jquery ajax jqXHR对象有一个statusText属性,但与angularjs我似乎无法找到我怎么可以在我的错误处理程序中访问此。不用说,我不能修改API,例如对于417状态代码可以返回不同的状态描述。 我发现我需要更改angularjs库,但在更新的情况下,这将不方便。我将不得不将xhr.responseText更改为xhr.statusText。我能否以某种方式覆盖我的代码中的这个函数,而不修改角库?Angularjs资源状态描述

xhr.onreadystatechange = function() { 
    if (xhr.readyState == 4) { 
     completeRequest(
      callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders()); 
    } 
    }; 

回答

0

您需要在模块配置期间创建一个httpInterceptor作为outlined here

// register the interceptor as a service 
$provide.factory('myHttpInterceptor', function($q) { 
    return function(promise) { 
    return promise.then(function(response) { 

     // do something on success 

    }, function(response) { 

     //do something for your 417 error 
     if(response.status == 417) { 
     alert("We've got a 417!"); 
     return $q.reject(response); 
     } 

     //some other error 
     return $q.reject(response); 
    }); 
    } 
}); 


$httpProvider.responseInterceptors.push('myHttpInterceptor'); 
+0

我已经有一个httpInterceptor。但在错误的响应不包含我所需要的。我必须将xhr.responseText更改为xhr.statusText。直到现在,我需要修改httpBackend提供程序,但我坚持,因为我不知道如何使用装饰方法 – TestersGonnaTest

1

这里的周围的工作来获取状态文本(如指出,一些移动浏览器从全成响应剔除数据:https://stackoverflow.com/a/28470163/1586498

我也发现在角$的HTTP .success和.error未通过StatusText,你必须使用。然后(响应)