我正在尝试通过检查user
对象是否存在来检查firebase user
是否已登录。但是,当我刷新页面时,firebase函数会在firebase返回user
对象并且用户被重定向之前运行异步页面加载,即使它们在技术上已登录。
见下面的代码:
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 :( */
});
答案 0 :(得分:1)
你需要你的解析器来返回一些东西。对于异步操作,这应该是一个promise(在Angular中,来自$q
服务)
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
});
}
}