【发布时间】:2017-02-10 09:29:40
【问题描述】:
我可以从 localStorage 登录、注销并显示已登录的用户信息,但是如果我使用不同的用户应用程序注销并再次登录,则会显示以前用户的信息!这不应该发生,因为我可以在 localStorage 中看到新的用户数据。如果我手动刷新页面,新数据会正确显示!
我需要这个应用程序来显示当前登录的用户数据,因为它已经在 localStorage 中可用..
routes.js
angular.module('app.routes', [])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('menu', {
url: '/side-menu',
templateUrl: 'templates/menu.html',
controller: 'menuCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'loginCtrl'
})
.state('menu.welcome', {
url: '/welcome',
views: {
'side-menu21': {
templateUrl: 'templates/welcome.html',
controller: 'welcomeCtrl'
}
}
})
$urlRouterProvider.otherwise('/user-type')
});
登录: 在这里,我通过 Web 服务对用户进行身份验证,该服务以 JSON 格式发回用户对象,该对象存储在 localStorage 中,键为“user”,并且工作正常。
.controller('loginCtrl', ['$scope', '$stateParams', '$state', '$http',
function ($scope, $stateParams, $state, $http) {
$scope.user = {
username: '',
password: ''
};
$scope.login = function(){
var apiUrl = "...";
return $http.post(apiUrl, $scope.user).then(function(response){
window.localStorage.setItem('user', angular.toJson(response.data));
$state.go('menu.welcome');
});
};
}
])
退出: 在这里,我通过从 localStorage 中删除 'user' JSON 对象来注销用户,并将他重定向回登录状态,它工作正常。
.controller('menuCtrl', ['$scope', '$stateParams', '$state',
function ($scope, $stateParams, $state) {
$scope.user = angular.fromJson(window.localStorage.getItem('user'));
$scope.logout = function(){
// here i'm removing user from localStorage
window.localStorage.removeItem('user');
$state.go('login');
};
}
])
菜单: 在这里,我正在显示从“menuCtrl”发送的用户信息(即使它在 localStorage 中可用,它也不会在此处更新登录用户的数据)
<h3 id="menu-heading1" class="left-menu-headings">{{user.first_name}} {{user.last_name}}</h3>
<h4 id="menu-heading2" class="left-menu-headings">{{user.email}}</h4>
我已经在注销功能中尝试了以下操作,但没有成功:
$window.localStorage.clear();
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
知道为什么它不显示来自 localStorage 的当前数据吗?
【问题讨论】:
-
也许在路由配置中设置页面不被缓存?另外,如果您只是从控制台获取 localStorage,您会看到该对象吗?
-
是的,我可以在 chrome 开发人员 -> 应用程序 -> 本地存储中看到更新的键和值
-
我在注销时使用
$window.location.reload(true);暂时解决了这个问题,如果我找到了一些解决方案来刷新登录时所有控制器的范围,我会报告..
标签: javascript html ionic-framework local-storage ionic2