如何将数据传递给 canActivate 服务守卫?
How to pass data to the canActivate service guard?
有路由定义:
{ path:'some_path', component: some_component, canActivate: some_service}
如何向 some_service 传递数据?
你可以这样传递:
首先在你的路由定义中添加数据属性:
{ path:'some_path', component: some_component, canActivate: some_service, data: {routeData: <what ever you want to pass>}}
然后在你的一些服务守卫中你可以访问数据:
canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> {
let routeData = route.data.routeData;
}
首先你应该添加一个服务实现 CanActivate 接口:
import { CanActivate, Router, ActivatedRouteSnapshot } from "@angular/router";
import { Injectable } from "@angular/core";
@Injectable()
export class MyCustomRouteActivator implements CanActivate {
constructor(private router: Router) {
//You could inject a service has your currentUserData . . .
}
canActivate(router: ActivatedRouteSnapshot) {
//You could get data from router service like params //id username ....
let canVisitPage = false;// add your conditional function here;
if (!canVisitPage) {
this.router.navigate([/404]);/ / choose your custom page path
}
}
}
然后将此服务添加到您的 app.module.ts :
providers:[....... MyCustomRouteActivator]
您终于可以在您的路线上使用它了:
//import MyCustomRouteActivator
{ path:'some_path', component: some_component, canActivate: [MyCustomRouteActivator]}
有路由定义:
{ path:'some_path', component: some_component, canActivate: some_service}
如何向 some_service 传递数据?
你可以这样传递:
首先在你的路由定义中添加数据属性:
{ path:'some_path', component: some_component, canActivate: some_service, data: {routeData: <what ever you want to pass>}}
然后在你的一些服务守卫中你可以访问数据:
canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> {
let routeData = route.data.routeData;
}
首先你应该添加一个服务实现 CanActivate 接口:
import { CanActivate, Router, ActivatedRouteSnapshot } from "@angular/router";
import { Injectable } from "@angular/core";
@Injectable()
export class MyCustomRouteActivator implements CanActivate {
constructor(private router: Router) {
//You could inject a service has your currentUserData . . .
}
canActivate(router: ActivatedRouteSnapshot) {
//You could get data from router service like params //id username ....
let canVisitPage = false;// add your conditional function here;
if (!canVisitPage) {
this.router.navigate([/404]);/ / choose your custom page path
}
}
}
然后将此服务添加到您的 app.module.ts :
providers:[....... MyCustomRouteActivator]
您终于可以在您的路线上使用它了:
//import MyCustomRouteActivator
{ path:'some_path', component: some_component, canActivate: [MyCustomRouteActivator]}