gpt4 book ai didi

angularjs - $rootScope.currentUser 在刷新时为空

转载 作者:行者123 更新时间:2023-12-03 13:21:32 26 4
gpt4 key购买 nike

我能够让 firebaseSimpleLogin 工作并将当前用户存储在 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);
});
}

}]);

我的主应用模块
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();
};

});

最佳答案

要将其存储在 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"));

关于angularjs - $rootScope.currentUser 在刷新时为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24193743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com