rest – 如何在角度服务调用中捕获401(或其他状态错误)?
发布时间:2020-12-17 07:32:30 所属栏目:安全 来源:网络整理
导读:使用$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('
使用$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 = {}; }); 但是,在使用服务时,我怎么能做类似的事情.这是我当前服务的外观: 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 = {}; } ); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |