如何在angularjs app中路由更改之前等待身份验证完成。
我正在使用angularfire简单身份验证。
您可以使用 example@gmail.com 和示例作为凭证来测试plunker。
我知道问题的原因。但不知道如何解决它......
实际上,当经过身份验证的用户转到' #/ home / 时,在 sahayiApp.run(function(){...})函数中检查条件 if(next.authRequired&&!$ rootScope.user){...} 。实际上,经过身份验证的用户可以通过此检查,但此代码在实际身份验证发生之前运行。那么在路由更改之前是否有任何方法进行身份验证...
答案 0 :(得分:6)
<强>更新强>
随着angularFire的发展,现在大部分已经过时了。查看此模块以获取更新版本:https://github.com/firebase/angularFire-seed/blob/master/app/js/module.simpleLoginTools.js
它修饰ng-cloak
以使用简单登录,并提供一些优化的帮助方法以及使用最新版本。
旧帖子
身份验证需要往返服务器。在SPA中,您通常不会在正常使用期间重新加载页面,因此在大多数情况下这实际上是多余的。
然而,通过对Angular的适度理解来解决并不困难。事实上,我教这个确切的场景作为在最近的研讨会上编写指令的一个例子。使用要点的Here's the gist I used和here's an example app。
请注意,如果您尝试克隆GitHub仓库,则需要抓取该特定代码(git checkout step3
),因为课程是按步骤教授的。
为了符合SO格式,这里是要点的内容。首先是指令:
angular.module('waitForAuth', [])
/**
* A service that returns a promise object, which is resolved once angularFireAuth
* is initialized (i.e. it returns login, logout, or error)
*/
.service('waitForAuth', function($rootScope, $q, $timeout) {
var def = $q.defer(), subs = [];
subs.push($rootScope.$on('angularFireAuth:login', fn));
subs.push($rootScope.$on('angularFireAuth:logout', fn));
subs.push($rootScope.$on('angularFireAuth:error', fn));
function fn() {
for(var i=0; i < subs.length; i++) { subs[i](); }
$timeout(function() {
// force $scope.$apply to be re-run after login resolves
def.resolve();
});
}
return def.promise;
})
/**
* A directive that hides the element from view until waitForAuth resolves
*/
.directive('ngCloakAuth', function(waitForAuth) {
return {
restrict: 'A',
compile: function(el) {
console.log('waiting');
el.addClass('hide');
waitForAuth.then(function() {
el.removeClass('hide');
})
}
}
})
/**
* A directive that shows elements only when the given authentication state is in effect
*/
.directive('ngShowAuth', function($rootScope) {
var loginState;
return {
restrict: 'A',
compile: function(el, attr) {
var expState = attr.ngShowAuth;
function fn(newState) {
loginState = newState;
el.toggleClass('hide', loginState !== expState );
}
fn(null);
$rootScope.$on("angularFireAuth:login", function() { fn('login') });
$rootScope.$on("angularFireAuth:logout", function() { fn('logout') });
$rootScope.$on("angularFireAuth:error", function() { fn('error') });
}
}
});
以及一些示例用法:
<style>
.hide { display: none; }
</style>
<script>
// include the waitForAuth module as a dependency
angular.module('myApp', ['waitForAuth'])
// you can use waitForAuth directly from your scripts
.controller('myController', function(waitForAuth) {
waitForAuth.then(function() {
/* do something after auth completes */
})
})
</script>
<!-- and you can use the directives in your views -->
<div ng-cloak-auth>Authentication has resolved.</div>
<div ng-show-auth="login">{{user.id}} is logged in</div>
<div ng-show-auth="logout">Logged out</div>
<div ng-show-auth="error">An error occurred during authentication</div>