Mar*_*ray 18 angularjs firebase angularfire
我能够使firebaseSimpleLogin工作并将当前用户存储在rootScope中.当我转到另一个页面并返回到feed页面时,所有内容都会加载,但是当我刷新$ rootScope.currentUser时为null.其他人遇到过这个问题吗?
我的app.run函数中有这段代码:
$rootScope.$on('$firebaseSimpleLogin:login',function(e, auth){
$rootScope.currentUser = User.find(auth.id);
});
Run Code Online (Sandbox Code Playgroud)
这是我的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);
});
}
}]);
Run Code Online (Sandbox Code Playgroud)
我的主要应用模块
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();
};
});
Run Code Online (Sandbox Code Playgroud)
lin*_*rik 28
如果您通过'刷新'意味着您在浏览器中点击F5将从内存中擦除$ rootscope,并且您将体验到null(基本上您的整个应用程序将'重新启动').
为了保持值,您需要将它们存储在cookie中或使用localStorage/sessionStorage.例如,使用$ window.sessionStorage.currentUser而不是使用$ rootscope.currentUser.
A. *_*ssi 10
将其存储在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"));
| 归档时间: |
|
| 查看次数: |
20148 次 |
| 最近记录: |