Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了rest – 如何在角度服务调用中捕获401(或其他状态错误)?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
使用$http我可以轻松地捕获像401这样的错误
$http({method: 'GET',url: 'http://localhost/Blog/posts/index.json'}).
success(function(data,status,headers,config) {
    $scope.posts = data;
}).
error(function(data,config) {
    if(status == 401)
    {
        alert('not auth.');
    }
    $scope.posts = {};
});

但是,在使用服务时,我怎么能做类似的事情.这是我当前服务的外观:

@H_252_1@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'];
在控制器调用发布之类的.
Post.index({},function success(data) { 
              $scope.posts = data; 
          },function err(error) {
           if(error.status == 401)
           {
             alert('not auth.');
           }
           $scope.posts = {};
         }
  );

大佬总结

以上是大佬教程为你收集整理的rest – 如何在角度服务调用中捕获401(或其他状态错误)?全部内容,希望文章能够帮你解决rest – 如何在角度服务调用中捕获401(或其他状态错误)?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。