angularjs ui-router stateparams invisible loses on page refresh

后端 未结 1 553
自闭症患者
自闭症患者 2021-01-05 14:45

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

$stateProvider.state(\'UserPanel\', {
    url: \'/user\',
    params: { userId: n         


        
相关标签:
1条回答
  • 2021-01-05 15:39

    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.

    0 讨论(0)
提交回复
热议问题