如何使用AngularJS单页面应用程序处理页面刷新

bio*_*tal 8 coffeescript angularjs

因为我学会了角度,所以有两个问题困扰我:

  1. 如何在用户刷新页面或点击后退按钮时恢复状态?

  2. 如何在属于不同控制器的作用域之间共享数据?

下面我展示了一个使用客户端会话存储的简单解决方案.它允许在用户刷新页面或点击后退按钮后共享公共数据和自动恢复状态.

注意:以下解决方案证明对回答以下问题至关重要:

如何让后退按钮与AngularJS ui-router状态机一起使用?

bio*_*tal 5

解决方案取决于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
Run Code Online (Sandbox Code Playgroud)

SessionService类定义的isAuthenticated属性(简单布尔)和user属性(一个复杂的对象).这些属性的值在使用sessionStoragejavascript提供的客户端本地对象存储/检索时自动进行字符串化/解析.

您可以根据需要添加更多属性.像$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')
Run Code Online (Sandbox Code Playgroud)

在服务中设置会话值

 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
Run Code Online (Sandbox Code Playgroud)

在UI中使用会话值(Jade模板)

div(ng-show="isAuthenticated")
    div Hello {{user.Name}}
Run Code Online (Sandbox Code Playgroud)

  • 我想对于我们这些不使用cofeescrpt/typescript等的大多数人来说,在我可以使用它之前必须转换(并可能引入错误)代码,效率很低. (6认同)