Danie A
Danie A

Reputation: 821

Ui-router: How to get next state params in transition

I'm using ui-router 1.0.0.beta.3. How can get I route parameters of next state during a transition?

index.run.js

$transitions.onStart({ to: '**' }, verifyAuth);

function verifyAuth(trans) {
  let nextState = trans.$to();
  if (Auth.verify(nextState.authGroup) === -1) {      
    return $state.go('login', { nextState: nextState.name, nextParams: nextState.params}); // this doesn't work
  }
}

I want to store them so I can redirect the user to the state + state params he was trying to access, after authentication is succeeded.

login.component.js

let nextState = this.$stateParams.nextState;
let nextParams = this.$stateParams.nextParams;
$state.go(nextState, nextParams);

Upvotes: 11

Views: 4236

Answers (1)

Chris T
Chris T

Reputation: 8216

the answer to your question is Transition.params()

function verifyAuth(trans) {
  let nextState = trans.to();
  let nextParams = trans.params();
  if (Auth.verify(nextState.authGroup) === -1) {      
    return $state.go('login', { nextState: nextState.name, nextParams: nextParams});
  }
}

However, I recommend studying how the ui-router 1.0 sample app performs authentication checks and login redirects:

This hook redirects the unauthenticated transition to the login state by returning a $state.target('login')

https://github.com/ui-router/sample-app-ng1/blob/master/app/global/requiresAuth.hook.js#L15-L24

In the login state, the "state to return to after login" is determined. It checks the original transition's destination using Transition.redirectedFrom().

https://github.com/ui-router/sample-app-ng1/blob/master/app/main/app.states.js#L44-L83

Upvotes: 16

Related Questions