在angularjs应用程序中重新加载页面会丢失数据

时间:2014-12-12 05:58:27

标签: javascript angularjs angularjs-scope angular-ui angular-ui-router

背景 我有一个多页angularjs应用程序。我有一个服务工厂对象,我在初始页面中加载了值。加载到服务工厂对象的值可通过相应的控制器js在不同的视图或页面中使用。如果用户尝试通过单击F5按钮进行浏览器刷新,则用户提供的值将丢失。

我的问题: 加载应用程序时,会显示“loginView”,用户输入的userId和密码将传递给第二个视图(summaryView.html)。我可以在第二页看到userId和密码显示正确。但是,如果我刷新我的第二个视图(summaryView.html),那么我将丢失所有值。该应用程序有点重置。

即使刷新或重新加载浏览器,我仍希望保留用户提供的数据。

我的代码:

**index.html**

<div ng-app="offlineInspectionApp">
<div ng-view></div>
</div>

<script>
var mainApp = angular.module("offlineInspectionApp", ['ngRoute']);
mainApp.factory( 'AuthService', function() {
var userCore = {userId : "anonymous" , password: "password", status :"online"};
return {userCore: function() { return userCore; }};
});

mainApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/summary', {
templateUrl: 'summaryView.html',
controller: 'SummaryViewController'
}).
when('/login', {
templateUrl: 'loginView.html',
controller: 'LoginViewController'
});
}]);

**LoginViewController.js**

angular.module("offlineInspectionApp").controller('LoginViewController',  function($scope,$http,$location, AuthService) {
$scope.authenticateUser = function() {
AuthService.userCore.userId = $scope.userId;
AuthService.userCore.password = $scope.password;
$location.path( "/summary" );
}       
});

**SummaryViewController.js**

angular.module("offlineInspectionApp").controller('SummaryViewController',  function($scope,$http,$location, AuthService) {
$scope.syncInspectionDetails = function(inspectionId) {
alert(AuthService.userCore.userId +' '+ AuthService.userCore.password);
};

I have two html files 'loginView.html' and 'summaryView.html'

1 个答案:

答案 0 :(得分:0)

流程

1-当用户输入正确的用户名和密码时,您将数据存储在角度变量中。这很好,它重定向到摘要页面。 AuthService.userCore与夏季页面的范围相同,因此它会在首次尝试时显示详细信息。 2-刷新页面时,清除在angularJs中声明的所有变量。因此,当您刷新页面时,您没有获得这些变量。

解决方案

有两种方式

1-将整个用户数据存储在cookie中,并在刷新时从cookie中获取数据 2-one登录complition使用任何访问令牌并将其存储在cookie中。并检查访问令牌,并在每次刷新时再次从后端获取数据。