Angularjs AngularFire routeProvider检查用户是否已登录
我试图通过检查用户对象是否存在来检查firebase用户是否已经登录。但是,当我刷新页面时,firebase函数会在firebase返回用户对象并重定向用户get之前异步运行页面加载,即使他们在技术上已登录 见下面的代码:Angularjs AngularFire routeProvider检查用户是否已登录,angularjs,firebase,firebase-authentication,route-provider,Angularjs,Firebase,Firebase Authentication,Route Provider,我试图通过检查用户对象是否存在来检查firebase用户是否已经登录。但是,当我刷新页面时,firebase函数会在firebase返回用户对象并重定向用户get之前异步运行页面加载,即使他们在技术上已登录 见下面的代码: app.config(['$routeProvider', '$locationProvider', '$waitForAuth','ngResource', function($routeProvider, $locationProvider, $waitForAu
app.config(['$routeProvider', '$locationProvider', '$waitForAuth','ngResource', function($routeProvider, $locationProvider, $waitForAuth, $ngResource) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'MainCtrl'
})
.when('/signup', {
templateUrl: 'views/signup.html',
controller: 'SignupCtrl'
})
.when('/classes', {
templateUrl: 'views/class_lesson.html',
controller: 'classLessonCtrl',
resolve: {
"firebaseUser": function($waitForAuth) {
//user = firebase.auth().currentUser;
firebase.auth().onAuthStateChanged(function(user) {
user = firebase.auth().currentUser;
if (user){
console.log("user signed in");
return user;
}
else {
//window.location.replace('/signup');
console.log(user);
console.log("user not signed in");
}
});
*
}
}
});
$locationProvider.html5Mode(true);
}]);
我四处搜索,发现一些人在使用Promise.all,以等待用户对象得到整理,但我不确定如何正确实现它。我能得到一些建议吗?还是有其他解决办法
var p = new Promise(function(resolve, reject) {
// Do an async task async task and then...
firebase.auth().onAuthStateChanged(function(user) {
user = firebase.auth().currentUser;
});
if(/* good condition */user!=null (?) {
resolve('Success!');
}
else {
reject('Failure!');
}
});
p.then(function() {
/* do something with the result */
}).catch(function() {
/* error :( */
});
您需要解析程序返回某些内容。对于异步操作,这应该是$q服务在Angular中的承诺
resolve: {
firebaseUser: function($waitForAuth) { // dunno what $waitForAuth is for
return $q(function(resolve) {
firebase.auth().onAuthStateChanged(resolve)
// will resolve with null if not logegd in
});
}
}