Javascript 为什么重新加载路由时AngularJS服务会重新初始化?
AngularJS服务被注入到两个单独的模块中。这会导致服务在第二个模块调用它时单独重新初始化。我已经使用FireFox调试器确认模块正在重新初始化。我怎样才能避免这个问题 具体情况如下: AngularJS应用程序在名为Javascript 为什么重新加载路由时AngularJS服务会重新初始化?,javascript,angularjs,Javascript,Angularjs,AngularJS服务被注入到两个单独的模块中。这会导致服务在第二个模块调用它时单独重新初始化。我已经使用FireFox调试器确认模块正在重新初始化。我怎样才能避免这个问题 具体情况如下: AngularJS应用程序在名为auth的模块中使用身份验证服务来管理身份验证问题。auth服务被导入一个消息模块,该模块管理对安全/message路由的访问,auth也被导入一个导航模块,该模块管理登录/注册以及用户浏览器中导航链接的可见内容。用户能够使用链接到导航模块的GUI工具成功登录,然后作为经过身份
auth
的模块中使用身份验证服务来管理身份验证问题。auth
服务被导入一个消息
模块,该模块管理对安全/message
路由的访问,auth
也被导入一个导航
模块,该模块管理登录/注册以及用户浏览器中导航链接的可见内容。用户能够使用链接到导航
模块的GUI工具成功登录,然后作为经过身份验证的用户成功重定向到安全的/message
路由,因为在重定向到/message
之前,auth.authenticated1
和auth.authenticated2
属性设置为true
但是,FireFox调试器确认问题在于,当用户刷新浏览器以重新加载/message
url模式时,auth
模块被重新初始化,将auth.authenticated1
和auth.authenticated2
的值设置回false,并因此向用户发送一条消息,表明他们未登录,即使他们在使用用户提供的有效凭据之前登录需要对下面的代码进行哪些特定更改,以便用户在重新加载页面时不会注销?
我希望AngularJS代码在加载或重新加载/message
路由时检查auth.authenticated2
的预先存在的值。如果auth.authenticated2=false
,则用户会收到一条消息说他们已注销。但是如果auth.authenticated2=true
,我希望用户能够在/message
路由上看到安全内容我不希望在重新加载路由时,以现在的方式将auth.authenticated2
自动重新设置为false
。
以下是message.html
中的代码,其中包含/message
路由的GUI元素:
<div ng-show="authenticated2()">
<h1>Secure Content</h1>
<div>
<p>Secure content served up from the server using REST apis for authenticated users.</p>
</div>
</div>
<div ng-show="!authenticated2()">
<h1>You are not logged in.</h1>
</div>
angular.module('message', ['auth']).controller('message', function($scope, $http, $sce, auth) {
$scope.authenticated2 = function() {
return auth.authenticated2;
}
//Other code calling REST apis from the server omitted here to stay on topic
});
以下是导航
模块的代码,该模块还注入了auth
服务:
angular.module('navigation', ['ngRoute', 'auth']).controller('navigation', function($scope, $route, auth, $http, $routeParams, $location) {
$scope.credentials = {};//from old navigation module
$scope.leadresult = "blank";
$scope.processStep = "start";
$scope.uname = "blank";
$scope.wleadid = "initial blank value";
$scope.existing = "blank";
$scope.tab = function(route) {
return $route.current && route === $route.current.controller;
};
$scope.authenticated1 = function() {
return auth.authenticated1;
}
$scope.authenticated2 = function() {
return auth.authenticated2;
}
$scope.login = function() {
auth.authenticate1($scope.credentials, function(authenticated1) {
//a bunch of stuff that does level 1 authentication, which is not relevant here
})
}
$scope.logout = auth.clear;
//some other methods to manage registration forms in a user registration process, which are omitted here because they are off-topic
$scope.pinForm = function(isValid) {//this method finishes authentication of user at login
if (isValid) {
$scope.resultmessage.webleadid = $scope.wleadid;
$scope.resultmessage.name = $scope.uname;
$scope.resultmessage.existing = $scope.existing;
var funcJSON = $scope.resultmessage;
auth.authenticate2(funcJSON, function(authenticated2) {
if (authenticated2) {
$location.path('/message');
$scope.$apply();//this line successfully re-directs user to `/message` route LOGGED IN with valid credentials
}
});
}
};
$scope.$on('$viewContentLoaded', function() {
//method that makes an unrelated call to a REST service for ANONYMOUS users
});
});
以下是auth.js
中的auth
服务的代码:
angular.module('auth', []).factory( 'auth', function($rootScope, $http, $location) {
var auth = {
authenticated1 : false,
authenticated2 : false,
usrname : '',
loginPath : '/login',
logoutPath : '/logout',
homePath : '/message',
path : $location.path(),
authenticate1 : function(credentials, callback) {
var headers = credentials && credentials.username ? {
authorization : "Basic " + btoa(credentials.username + ":" + credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) { auth.authenticated1 = true; }
else { auth.authenticated1 = false; }
callback && callback(auth.authenticated1);
}).error(function() {
auth.authenticated1 = false;
callback && callback(false);
});
},
authenticate2 : function(funcJSON, callback) {
$http.post('/check-pin', funcJSON).then(function(response) {
if(response.data.content=='pinsuccess'){
auth.authenticated2=true;
callback && callback(auth.authenticated2);
}else {
auth.authenticated2=false;
auth.authenticated2 = false;
callback && callback(false);
}
});
},
clear : function() {
$location.path(auth.loginPath);
auth.authenticated1 = false;
auth.authenticated2 = false;
$http.post(auth.logoutPath, {}).success(function() { console.log("Logout succeeded");
}).error(function(data) { console.log("Logout failed"); });
},
init : function(homePath, loginPath, logoutPath) {
auth.homePath = homePath;
auth.loginPath = loginPath;
auth.logoutPath = logoutPath;
}
};
return auth;
});
routeProvider
由应用程序的主js
文件管理,即hello.js
,如下所示:
angular.module('hello', [ 'ngRoute', 'auth', 'home', 'message', 'public1', 'navigation' ])
.config(
function($routeProvider, $httpProvider, $locationProvider) {
$locationProvider.html5Mode(true);/* This line is one of 3 places where we set natural urls to remote the default # */
$routeProvider.when('/', {
templateUrl : 'js/home/home.html',
controller : 'home'
}).when('/message', {
templateUrl : 'js/message/message.html',
controller : 'message'
}).when('/public1', {
templateUrl : 'js/public1/public1.html',
controller : 'public1'
}).when('/register', {
templateUrl : 'js/navigation/register.html',
controller : 'navigation'
}).otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}).run(function(auth) {
// Initialize auth module with the home page and login/logout path
// respectively
auth.init('/checkpin', '/login', '/logout');
});
不是一个完整的答案,在这里更改确切的代码。但是足够建造一些漂亮的东西 您不应该在身份验证服务中仅显式使用布尔值。据我所知,您没有使用成功身份验证后从服务器接收到的任何数据。因此,每当你刷新时,一切都会丢失。您的代码中没有任何内容可以从刷新中恢复 理想情况下,您应该有一个令牌或cookie之类的东西。cookie将被保存,并可在刷新后恢复,因此在启动身份验证服务时,您可以检查该cookie是否存在 您还可以保存一个令牌,该令牌可用于访问indexedDB内的API或类似的内容。正如我之前所说的,在auth服务的启动期间,您必须检查该令牌是否存在 如果需要更多信息,请检查Oauth2。尽管Oauth2不是身份验证API而是授权API,但密码授予类型是可以使用的。了解如何构建一个坚实的系统。其他授权类型主要只关注OAuth的授权端 因为这里需要代码,所以它是:
when creating_service:
if exists(cookie) or exists(token) and valid(cookie) or valid(token):
mark_service_as_logged_in()
如果伪代码比文字更好。@CodeMed您要求的是他为您编写一个身份验证系统。这不是一件小事。它完全绑定到您的服务器。您可能会考虑对Cookie /认证令牌做更多的研究,然后在卡住时再问一个更窄的问题。代码>请显示代码。OP请求代码希望你是在开玩笑吧?cookie必须在服务器端完成。很抱歉,您要求的是一个理论上的答案,因为您似乎不知道身份验证是如何工作的。此用户的回答并未开始解决OP中所述的问题。OP明确规定:需要对以下代码进行哪些特定更改,以便用户不会在重新加载页面时注销?