AngularJS. Retain state after page reload

2019-06-05 19:18发布

问题:

I am using UI Router with html5Mode enabled, states are loaded from JSON.

Expected behavior after F5 or when pasting URL is, respectively, having current state reloaded or navigating to the said state, instead the initial application state is loaded.

For e.g. root/parent/child gets redirected to root/.

By the way, navigating with ui-sref works fine.

So, how can the state be retained after page reload?

回答1:

In order to retain the state of page after reload app, a url represent the state should be gave. when you include ui-route module, url will be parsed and sent to corresponding state. You don't need to parse the url handly in most cases, ui-route born to do this.



回答2:

Please can you post your code here? Specifically the $stateProvider. This is an example of a correct $stateProvider and it works fine:

$stateProvider.state('main.admin', {
    url: '/admin',
    resolve: {},
    views: {
        'main-content@main': {
            controller: 'AdminController as admin',
            templateUrl: 'main/admin/admin.tpl.html'
        }
    }
});


回答3:

Seems a bit hacky, but works for now.

app.run(['$location', '$state', function ($location, $state) {
  function stateFromUrl () {
    var path = $location.path(),
        hash = $location.hash();

    // do JSON states map parsing and find a corresponding to the URL state

    return state;
  }

  if (stateFromUrl) {
    $state.go(stateFromUrl);
  } else {
    $state.go('home'); // initial state
  }
}]);