将数据从 Guard 传递到组件

Pass Data from Guard to Component

我的子路由组件正在查询 API 中的一些数据。目前,我正在通过检查 API 返回的数据来检查组件中作为路由参数提供的 id 是否有效。

我认为这是一种糟糕的风格,并希望将检查放入一个守卫中,该守卫在组件被激活之前检查提供的参数是否有效。

不过,我也想节省时间和资源。这将需要两个 API 请求。因此我想知道是否有可能将数据从守卫传递到组件。我考虑过与路由参数一起传递,但 canActivate 只提供一个只读的 ActivatedRouteSnapshot

因此我的问题是:是否可以将数据从守卫传递到组件?或者在这种情况下是否有另一种(甚至更好的)方法来节省资源并防止多次 API 请求?

我认为您正在寻找 Resolver。使用解析器,您可以在加载组件之前在路由转换上加载数据。设置与守卫大致相同。

@Injectable()
export class YourResolver implements Resolve<YourObject> {

    constructor(private dataService: DataService) {
    }

    resolve(route: ActivatedRouteSnapshot): Observable<YourObject> {
        return this.dataService.getData().do(data=>{
           // you could potentially handle a redirect here if need be/
         });
    }
}

然后在你的路线设置中做

       {
            path: 'yourComponent', component: YourComponent,
            resolve: {
                data: YourResolver
            }, outlet: 'content'
        },

Angulars canActivate 在您的组件之前触发。在 canActivate 中,您可以访问已激活的路由器,并使用 api 检查您想要的 "id" 或 参数,并在收到 api 的结果后,您可以 return真假。如果你 return false,你的控制器根本不会被触发。 因此,检查用户权限的正确过程是在 canActivate class 中检查它们。不要忘记,您可以链接您的 canActivate 过滤器,并按给定顺序检查它们。

path:"doSomethingById/:id", controller: ExampleController,  canActivate: [AuthGuard, IdChek]

在上面的示例中,只有当 AuthGuard return 为真时,IdCheck 才会 运行。只有当它们都 return 为真时,你的控制器才会被解雇。