Chr*_*emm 6 canactivate angular
我的子路由组件正在查询API中的一些数据.目前我正在检查组件,如果通过检查API返回的数据,作为路由参数提供的id是有效的.
我认为这是一种糟糕的风格,并希望将检查放入一个警卫,在组件被激活之前检查提供的参数是否有效.
但是,我也想节省时间和资源.这将需要两个API请求.因此,我想知道是否有可能将数据从防护装置传递给组件.我想过传递路线参数,但canActivate只提供一个ActivatedRouteSnapshot只读的.
因此我的问题是:是否可以将数据从防护组件传递到组件?或者在这种情况下是否有另一种(甚至更好的)方法来节省资源并防止多个API请求?
我想你正在寻找一个解析器.使用解析程序,您可以在组件加载之前加载路径转换上的数据.设置与防护装置大致相同.
@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/
});
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的路线设置做
{
path: 'yourComponent', component: YourComponent,
resolve: {
data: YourResolver
}, outlet: 'content'
},
Run Code Online (Sandbox Code Playgroud)