我能够使firebasesimplellogin工作并将当前用户存储在rootScope中。当我转到另一个页面并返回到提要页面时,一切都加载了,但是当我刷新$rootScope。currentUser为空。还有其他人有这个问题吗?
我有这段代码在我的app.run函数:
$rootScope.$on('$firebaseSimpleLogin:login',function(e, auth){
$rootScope.currentUser = User.find(auth.id);
});
这是我的FeedCtrl它试图加载用户的帖子
app.controller('FeedCtrl',['$scope', '$rootScope','User','Auth','Post',function($scope, $rootScope,User,Auth,Post){
populateFeed();
console.log($rootScope.currentUser);
$scope.logout = function(){
Auth.logout();
};
$scope.savePost = function(){
Post.create($scope.post).then(function(post){
$scope.post.text = "";
});
};
function populateFeed(){
$scope.posts = {};
angular.forEach($rootScope.currentUser.posts,function(id){
$scope.posts[id] = Post.find(id);
});
}
}]);
My Main app Module
var app = angular.module('myapp',['ui.router','firebase']);
app.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('/',{
url: '/',
controller: 'MainCtrl',
templateUrl: 'views/index.html'
})
.state('feed',{
url: '/feed',
controller: 'FeedCtrl',
templateUrl: 'views/feed.html',
authenticate: true
})
.state('login',{
url: '/login',
controller: 'LoginCtrl',
templateUrl: 'views/login.html'
})
.state('signup',{
url: '/signup',
controller: 'LoginCtrl',
templateUrl: 'views/signup.html'
})
.state('settings',{
url: '/settings',
controller: 'SettingsCtrl',
templateUrl:"views/settings.html"
})
.state('profile',{
url: '/:slug',
controller: 'ProfileCtrl',
templateUrl: 'views/profile.html'
})
.state('profile-about',{
url: '/:slug/about',
controller: 'ProfileCtrl',
templateUrl: 'views/profile.html'
});
$urlRouterProvider.otherwise('/');
})
.constant('FIREBASE_URL','https://{FIREBASE}.firebaseio.com/')
.run(function($rootScope, $state,FIREBASE_URL, $firebaseSimpleLogin, User, Auth){
$rootScope.$on('$stateChangeStart',function(event, next){
if(next.authenticate && !User.getCurrentUser()){
$state.go('login');
}
});
$rootScope.$on('$firebaseSimpleLogin:login',function(e, auth){
$rootScope.currentUser = User.find(auth.id);
});
$rootScope.$on('$firebaseSimpleLogin:logout',function(){
delete $rootScope.currentUser;
$state.go('login');
});
$rootScope.logout = function(){
Auth.logout();
};
});
如果你通过'刷新'意味着你在浏览器中按F5,将从内存中擦除你的$rootscope,你将得到null返回,因为你的经验(基本上你的整个应用程序将被'重新启动')。
为了持久化值,您需要将它们存储在cookie中或使用localStorage/sessionStorage。例如,不要使用$rootscope。
将其存储在localStorage中:window.localStorage美元。setItem("currentUser",currentUser);
或以json格式存储:window.localStorage美元。setItem("currentUser angular.toJson (currentUser));
要从那里得到它:var currentUser = $window.localStorage.getItem("currentUser");
或者使用第二种方式保存:var currentUser = JSON.parse($window.localStorage.getItem("currentUser"));