Search code examples
javascriptangularjsangular-ui-router

UI Router $stateParams are only readable


I'm currently passing in an id to a new state with $stateParams. Works fine, but what if the user reloads the page? Obviously, there will not be any values in $stateParams. The work around for this was to load the $stateParam id into localStorage on initial page load. On reload, if the id of $stateParams doesn't exist, then manually assign it. For example:

// Ensure params are set when page is reloaded
if (!$stateParams.id) {
  $stateParams.id = localStorageService.get('campaignId');
  $state.go($state.current, $stateParams);
}

On my local machine this works. However on my development server, I'm getting this error:

Cannot assign to read only property 'id' of object '#<Object>'.

Is there a way I can make $stateParams writable?

Hope this makes sense, thanks in advance.


Solution

  • Since I couldn't find a solution to actually write to $stateParams, I just created a new object for this situation.

    var stateParamsClone = {};
    // Ensure params are set when page is reloaded
    if (!$stateParams.id) {
      stateParamsClone.id = localStorageService.get('campaignId');
      $state.go($state.current, stateParamsClone);
    }