【问题标题】:How to catch a 401 (or other status error) in an angular service call?如何在角度服务调用中捕获 401(或其他状态错误)?
【发布时间】:2013-09-24 19:44:48
【问题描述】:

使用 $http 我可以轻松捕获 401 之类的错误:

$http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'}).
success(function(data, status, headers, config) {
    $scope.posts = data;
}).
error(function(data, status, headers, config) {
    if(status == 401)
    {
        alert('not auth.');
    }
    $scope.posts = {};
});

但是,在使用服务时,我该如何做类似的事情。这是我当前服务的外观:

myModule.factory('Post', function($resource){
    return $resource('http://localhost/Blog/posts/index.json', {}, {
          index: {method:'GET', params:{}, isArray:true}
    });
});

(是的,我只是在学习角度)。

解决方案(感谢 Nitish Kumar 和所有贡献者)

在 Post 控制器中,我这样调用服务:

function PhoneListCtrl($scope, Post) {
    $scope.posts = Post.query();
}
//PhoneListCtrl.$inject = ['$scope', 'Post'];

根据所选答案的建议,现在我这样称呼它并且它有效:

function PhoneListCtrl($scope, Post) {
    Post.query({},
    //When it works
    function(data){
        $scope.posts = data;
    },
    //When it fails
    function(error){
        alert(error.status);
  });
}
//PhoneListCtrl.$inject = ['$scope', 'Post'];

【问题讨论】:

    标签: rest angularjs


    【解决方案1】:

    在控制器调用 Post like .

    Post.index({}, 
              function success(data) { 
                  $scope.posts = data; 
              },
             function err(error) {
               if(error.status == 401)
               {
                 alert('not auth.');
               }
               $scope.posts = {};
             }
      );
    

    【讨论】:

      【解决方案2】:

      资源返回承诺,就像 http。只需挂钩错误解决方案:

      Post.get(...).then(function(){
        //successful things happen here
      }, function(){
        //errorful things happen here
      });
      

      AngularJS Failed Resource GET

      【讨论】:

        【解决方案3】:

        $http 是一项服务,就像 $resource 是一项服务一样。

        myModule.factory('Post', function($resource){
          return $http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'});
        });
        

        这将返回承诺。您还可以在您的工厂和链中使用承诺,以便您的工厂(服务)为您完成所有错误处理。

        【讨论】:

          猜你喜欢
          • 2015-02-14
          • 1970-01-01
          • 2018-05-31
          • 1970-01-01
          • 2017-01-04
          • 2018-12-02
          • 2014-12-31
          • 2015-05-21
          • 2014-03-05
          相关资源
          最近更新 更多