angularjs ui-router stateparams invisible loses on page refresh

百般思念 提交于 2019-11-30 05:39:12

问题


Im working on a angular project, where i have set my states as shown below.

$stateProvider.state('UserPanel', {
    url: '/user',
    params: { userId: null },
    views: {
        'content@': {
            templateUrl: '/AngViews/UserPanel/UserPanel.UserDetails.html'
        }
    }
});

when i navigate to the view, it takes the params with it, so this part is working.

But when i update the page, it's loses the params. I know that if i defined the params in the url variable it will work. but i want to make it invisible.

I have found something like this, but don't know if it's gonna fix my problem. can't get it working if it does. anyone who can explain how this can be done?

Thanks for your time


回答1:


I faced the same problem and solved it with this code

angular.module('app').run(function($rootScope, $state, localStorageService) {

  $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
   var prefix = "stateParams.";
   var fromStateName = prefix + fromState.name;
   var toStateName = prefix + toState.name;
   var f = true;
   for (var k in toState.params) {
     f = f && (JSON.stringify(toParams[k]) == JSON.stringify(toState.params[k]));
   }
   if (f && localStorageService.get(toStateName) != null) {
     event.preventDefault();
     var savedToParams = localStorageService.get(toStateName); //retrieving toParams from local storage
     localStorageService.remove(toStateName);
     for (var k in toState.params) {
       toParams[k] = savedToParams[k]; //update only the params {} not url params
     }
     $state.transitionTo(toState,toParams);
   } else {
     var toSave = {};
     for (var k in toState.params) {
       toSave[k] = toParams[k]; //save only the params {} not url params
     }
     localStorageService.set(toStateName,toSave);
   }
  });

});

Gist

I try to use the localStorageService to 'cache' the params between state transitions.

when going from state A to state B , I remove the params previously stored for A.

I then check to see if the params that are being sent to B match the params in the state definition of B, and if they do match I load the params from the localStorage , because this means that the user has hit refresh and the params got reset.

I tested this code on a couple of cases , but it is still not fully tested.



来源:https://stackoverflow.com/questions/32602345/angularjs-ui-router-stateparams-invisible-loses-on-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!