AngularJS 中的 $http 错误处理

Sur*_*rya 3 ios angularjs cordova-3 angularjs-http

我的 AngularJS 项目中的 $http 无法识别 iOS 上的 40X(401,403,405...) 错误。我使用的是 1.2.10 AngularJS 版本和 Cordova 3.4.0 版本。

下面是我正在使用的代码:

TE_SERVICES.factory('hello',function ($http,$rootScope) {
return {
loginUser: function(userCredentials,successCallback,errorCallback){
          $http({
               method: "GET",
               url: "data/example.json",
               headers: {"Authorization":'Basic '+userCredentials},
             }).then(function(response){
                                successCallback(response.data);
                                console.log("Success------"+JSON.stringify(response))
             },function(data, status, headers, config){
                                errorCallback(data);
                                console.log("Error------"+JSON.stringify(data)+" "+status)
             })

        }
    }
 });

hello.loginUser($rootScope.encodedUserCredencials,function(persons) {
                // success handler
            }, function(data) {
                // error handler
                console.log(data.status+"===="+status)
                });
Run Code Online (Sandbox Code Playgroud)

data.status返回 0,状态返回未定义。请帮我解决这个问题。

试图将域包含在 IOS 的白名单中。但没有解决方案:( 它仍然给出相同的响应。

但是相同的代码在 Android 中运行得非常好。请帮我解决这个问题。

提前致谢 :)

Kon*_*ass 5

所以你使用$httpfrom angular。你使用error回调函数还是then回调函数中的第二个函数?

例子

$http.get("someUrl")
  .success(function(response){}) // if http code == 200
  .error(function(response){}) // else
Run Code Online (Sandbox Code Playgroud)

或者使用then,可以使用 2 个函数。第一个是 onSuccess,第二个是 onError 函数。

$http.get("someUrl")
  .then(function(response){
            // if http code == 200
   },
    function(response){
            // else
   }); 
Run Code Online (Sandbox Code Playgroud)

response参数还包含错误代码。

考虑使用 a$httpInterceptor在同一位置处理所有错误代码,而不是在每个 http 回调中处理它们。

更新:看来,成功回调的角度文档不完整/错误。它没有在那里传递 4 个参数。它确实传递了一个response对象,该对象包含有关请求+响应的所有信息和传递的数据。

更新编辑

不要自己编写回调。使用角度承诺:

TE_SERVICES.factory('hello',function ($http,$rootScope) {
   return {
       loginUser: function(userCredentials){
          return $http({
             method: "GET",
             url: "data/example.json",
             headers: {"Authorization":'Basic '+userCredentials},
          }).then(function(response){
             return response.data;                                    
          },function(response){
             return response;                                
          });    
        }
    }
 });

hello.loginUser($rootScope.encodedUserCredencials)
     .then(function(persons) {                // success handler

     }, function(data) { // error handler
       console.log(data);
     });
Run Code Online (Sandbox Code Playgroud)

试试这个并告诉我是否console.log记录了一些东西。

  • 根据 https://docs.angularjs.org/api/ng/service/$http “`$http` 遗留承诺方法 `success` 和 `error` 已被弃用。请使用标准的 `then` 方法。” (2认同)