如何使用AngularJS单页面应用程序处理页面刷新
因为我学会了角度,所以有两个问题困扰我:
>当用户刷新页面或点击后退按钮时,如何恢复状态? 下面我展示了一个使用客户端会话存储的简单解决方案.它允许在用户刷新页面或点击后退按钮后共享公共数据和自动恢复状态. 注意:以下解决方案证明对回答以下问题至关重要: How do I get the Back Button to work with an AngularJS ui-router state machine?
解决方案取决于下面显示的SessionService类.语法是coffeescript.
SessionService类 class SessionService scopes:[] setStorage:(key,value) -> scope[key] = value for scope in @scopes value = if value is undefined then null else JSON.stringify value sessionStorage.setItem key,value getStorage:(key)-> sessionValue = sessionStorage.getItem key if sessionValue == "undefined" return null JSON.parse sessionValue register:(scope)-> for key,value of sessionStorage scope[key] = if value? and value != "undefined" then JSON.parse(value) else null @scopes.push scope scope.$on '$destroy',=> @scopes = @scopes.filter (s) -> s.$id != scope.$id clear: -> @setStorage(key,null) for key of sessionStorage isAuthenticated: -> @accessor 'isAuthenticated',value user:(value=null) -> @accessor 'user',value # other storage items go here accessor:(name,value)-> return @getStorage name unless value? @setStorage name,value angular .module 'app.Services' .service 'sessionService',SessionService SessionService类定义isAuthenticated属性(简单bool)和用户属性(复杂对象).这些属性的值在使用javascript提供的客户端本地sessionStorage对象存储/检索时自动进行字符串化/解析. 您可以根据需要添加更多属性.与$rootScope一样,您可以节省地添加属性.与$rootScope不同,页面刷新或单击后退按钮后,属性值仍然可用. 该服务允许在其中注册任意数量的范围.注册范围时,sessionStorage中的所有存储值都将自动分配给该范围.这样,所有已注册的作用域始终可以访问所有会话属性. 更新属性值时,所有已注册的作用域都会更新其对应的值. 当角度破坏范围时,它会自动从已注册范围列表中删除,以节省浪费资源. 如果用户刷新页面或点击后退按钮,则强制角度应用程序重新启动.通常这意味着您必须重建当前状态. SessionService会自动为您执行此操作,因为每个作用域在应用程序初始化期间注册时都会从本地存储中恢复其值. 因此,现在很容易解决在作用域之间共享数据以及在用户刷新或按下后退按钮时恢复值的问题. 下面是一些示例角度代码,展示了如何使用SessionService类. 在某些Controller中为SessionService注册一个范围 angular .module 'app' .controller 'mainCtrl',($scope,$state,session,security) -> #register the scope with the session service session.register $scope #hook up the 'login' method (see security service) $scope.login = security.login # check the value of a session property # it may well be true if the page has been refreshed if session.isAuthenticated $state.go('home') else $state.go('login') 在服务中设置会话值 class SecurityService @$inject:['$http','sessionService','api'] constructor:(@http,@session,@api) -> login:(username,password) => @http.get "#{@api.base}/security/login/credentials/#{username}/#{password}" .success (user)=> @session.isAuthenticated = true @session.user = user .error (ex)=> # process error angular .module 'app' .service 'securityService',SecurityService 在UI中使用会话值(Jade模板) div(ng-show="isAuthenticated") div Hello {{user.Name}} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |