user2957271
user2957271

Reputation: 192

Parameters in Angular2 ui-router

I work with angular2 and ui-router (https://ui-router.github.io/docs/latest/modules/ng2.html). I use the stateService in order to move from a state to another in typescript code. How can i get passed parameter in the new component? Here some code of the caller component:

private editUser(user: User): void {
    this.uiRouter.stateService.go("home.userEdit", { userToEdit: user }, null);
}

And here the code of the called component:

constructor(private uiRouter: UIRouter, private usersService: UsersService) {
    if (uiRouter.globals.params != null) {
        //this.user = user;
    }
}

The problem is that uiRouter.globals.params has always one single property named "#" with null value. What is the problem?

Upvotes: 0

Views: 2280

Answers (1)

Chris T
Chris T

Reputation: 8216

The globals object is not updated until after the transition is complete. Inject the current Transition object instead and ask it for its parameters.

constructor(private trans: Transition, private usersService: UsersService) {
    var params = trans.params();

}

Note: you can also use resolve to fetch your user before the component is rendered.

var state = {
  name: 'user',
  component: UserComponent,
  resolve: [
    { 
      token: 'user', deps: [Transition, UserService], 
      resolveFn: (trans, svc) => 
        svc.getUser(trans.params().userId)
    }
  ]
}

@Component({
 ...
}) 
class UserComponent {
  @Input('user') user: User;
  constructor() {
  }
}

Upvotes: 2

Related Questions