1

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

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

3 回答 3

1

这是获取 StatusText 的解决方法(正如所指出的,某些移动浏览器会从成功的响应中删除 DATA:https ://stackoverflow.com/a/28470163/1586498

我还发现 Angular 中 $http 上的 .success 和 .error 没有通过 StatusText,你必须使用 .then(response)

于 2015-02-12T05:49:17.620 回答
0

AngularJS 1.2.16添加了对 statusText 的支持。

于 2014-05-19T11:03:17.487 回答
0

您需要在模块配置期间按照此处所述创建一个 httpInterceptor。

// 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');
于 2013-01-23T14:25:05.333 回答