Javascript 视图在使用$http.get时关闭?当401作为响应返回时,ng视图关闭?
我有一个身份验证代码,当我得到一个成功消息,如200响应状态,然后它的罚款,但如果我得到401页应该显示错误,因为我已经设置了一些错误状态,但这没有发生,我得到的看法也刷新,结果是空白。请帮忙Javascript 视图在使用$http.get时关闭?当401作为响应返回时,ng视图关闭?,javascript,ajax,angularjs,angularjs-directive,ng-view,Javascript,Ajax,Angularjs,Angularjs Directive,Ng View,我有一个身份验证代码,当我得到一个成功消息,如200响应状态,然后它的罚款,但如果我得到401页应该显示错误,因为我已经设置了一些错误状态,但这没有发生,我得到的看法也刷新,结果是空白。请帮忙 app.controller('MyController', ['$scope', '$location', '$http','$rootScope','$route','$localStorage', function ($scope, $location, $http, $rootScope,$rou
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('unauthorized', function() {
// ... some code to handle tokens, cookies, whatever ... set to null
$location.path('/login');
});