简体   繁体   中英

Angular 2 canActivate : retrieve value in component

How can I get the value of the canActivate param of the routing from inside the component ?

{
    path: "dashboard",
    component: DashboardComponent,
    canActivate: [AuthGuard] // => This one
}

I'm asking that because I would like to show/hide elements in the template, depending the user is connected or not.

So, for now, I'm calling the authentication service inside the component but then it makes two calls, one from the guard, the other from the component.

ngOnInit() {
    this.authService.canAccess().then(
        auth => this.canAccess = auth
    );
}

Is there a way to subscribe to some routing event and get the value of the canActivate property ?

Maybe use resolver? It won't initiate component until some data is fetched

{
    path: 'path',
    component: SomeComponent,
    resolve: {someVarYouNeed: someResolver}
}

class someResolver implements Resolve

constructor (private service: MyService) {
    return service.getData.map(data => data.json())
}

in your component:

ngOnInit() {
    this.varYouNeed = this.route.snapshot.data['someVarYouNeed'];
}

Remember that resolver should return Observable and data from this Observable is attached to route data as property according to name used in resolver in routes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM