[英]View goes off while using $http.get in angular? ng-view goes off when 401 is returned as response?
我有一个身份验证代码,当我收到200响应状态的成功消息时,它很好,但是如果我收到401,则页面应该显示错误,因为我已经设置了一些错误状态,但是这种情况不会发生,并且我得到的视图也会刷新,原来是空白。 请帮忙
app.controller('MyController', ['$scope', '$location', '$http','$rootScope','$route','$localStorage', function ($scope, $location, $http, $rootScope,$route, $localStorage) {
$scope.username = "";
$scope.password = "";
$scope.ipsenData = {};
$scope.username="";
$scope.password="";
$scope.invalidUser="";
/*Functionalities of the Application*/
$scope.login = function () {
$http.post('/ipsen/login', {
username: $scope.username,
password: $scope.password
}).
success(function (data, status, headers, config) {
if(status===200){
console.log("Login Successful");
$http.get('/ipsen/getrole?userName='+$scope.username)
.success(function (data, status, headers, config) {
if(data.rows[0].RoleName==="Ipsen Manager"){
var data = data.rows[0];
/*Username and Role Storage*/
$localStorage.username=$scope.username;
$localStorage.FirstName=data.FirstName;
$localStorage.LastName=data.LastName;
$localStorage.OrganizationName=data.OrganizationName;
$localStorage.RoleName=data.RoleName;
$localStorage.Email=data.Email;
$location.path('/customers').replace();
}
else{
var data = data.rows[0];
/*Username and Role Storage*/
$localStorage.FirstName=data.FirstName;
$localStorage.LastName=data.LastName;
$localStorage.OrganizationName=data.OrganizationName;
$localStorage.RoleName=data.RoleName;
$localStorage.Email=data.Email;
$location.path('/furnacelist/'+$scope.username+"/"+"customer").replace();
}
/**/
})
.error(function (data, status, headers, config) {
console.log(data);
});
}
}).
error(function (data, status, headers, config) {
if(status === 401){
$scope.invalidUser="Please Enter Valid Username & Password";
}
});
};
}]);
您可以设置如下所示的拦截器,这可能会有所帮助,以便在401上,您的用户只会停留在登录页面上。
function APIInterceptor($rootScope, $q) {
var service = this;
service.responseError = function(response) {
console.log("in responseError", response); // just to see the error initially
if (response.status === 401) {
$rootScope.$broadcast('unauthorized');
return $q.reject(response);
}
return response;
};
}
然后,将拦截器放入处理路由的配置文件中。
$httpProvider.interceptors.push('APIInterceptor');
使用以下代码rootScope.$on
在.run
使用rootScope.$on
。
$rootScope.$on('unauthorized', function() {
// ... some code to handle tokens, cookies, whatever ... set to null
$location.path('/login');
});
我还有其他一些遗漏,但我想您明白了。 基本上,您想在其中添加一个拦截器来处理您的请求和响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.