简体   繁体   English

Angular 2 canActivate:在组件中检索值

[英]Angular 2 canActivate : retrieve value in component

How can I get the value of the canActivate param of the routing from inside the component ? 如何从组件内部获取路由的canActivate参数的值?

{
    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 ? 有没有办法订阅一些路由事件并获取canActivate属性的值?

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 请记住,解析程序应返回Observable,并且此Observable中的数据将根据路由中解析程序中使用的名称作为属性附加到路由数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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