Javascript 创建用于多种用途的角度解析器
我正在寻找一种方法来使用一个角度路线解析,用于我的所有路线,但参数不同: 目前,我有一些类似于:Javascript 创建用于多种用途的角度解析器,javascript,angular,routes,resolver,Javascript,Angular,Routes,Resolver,我正在寻找一种方法来使用一个角度路线解析,用于我的所有路线,但参数不同: 目前,我有一些类似于: { path: 'user/:any', component: UserprofileComponent, resolve: { ProfiledUser: UserprofileResolver } }, { path: 'user/:any', component: UserprofileComponent,
{
path: 'user/:any',
component: UserprofileComponent,
resolve: { ProfiledUser: UserprofileResolver }
},
{
path: 'user/:any',
component: UserprofileComponent,
resolve: { ProfiledUser: UserprofileResolver }
data: {load: 'userprofile/admin'},
},
配置文件用户解析:
resolve(route: ActivatedRouteSnapshot) {
return this.GlobalService.Get('/userprofile/admin');
}
事实上,我正在寻找一种方法,为解析器本身使用GlobalService
中的Get
函数正在使用的参数
我以前做过一些理论上可行的事情:
path: 'family/panel',
component: FamilyCoreComponent,
canActivate: [PermissionGuardService],
data: {roles: [0]},
其中可以激活权限保护:
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean>|boolean {
var requirementRole = next.data.roles[0];
这是一个好办法吗?如果是这样的话,我该怎么做才能使它最有效呢?好问题,也让我挠头了好一阵子:) 因此,让我们深入研究我对这个问题的解决方案 当使用
Resolver
时,我们可以用我们喜欢的任何东西(函数/类)替换Resolver
@NgModule({
进口:[
RouterModule.forRoot([
{
路径:'team/:id',
组件:团队组件,
决心:{
团队:'teamResolver'
}
}
])
],
供应商:[
{
提供:'teamResolver',
useValue:(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot)=>“团队”
}
]
})
这个片段直接来自
因此,在本例中,您可以在useValue
行中添加一些额外的参数,如下所示
useValue:(路由:ActivatedRouteSnapshot,状态:RouterStateSnashot)=>
新的ResolverWithParamsResolver(
路线,,
国家,,
“自定义链接”
).resolve()
您的ResolverWithParamsResolver
可能有,类似于下面的代码片段
export interface ResolverWithParamModel<T> {
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
linkParam: string
): Observable<T> | Promise<T> | T;
}
// Custom resolver
@Injectable()
export class ResolverWithParamsResolver implements ResolverWithParamModel<any> {
constructor(
private route: ActivatedRouteSnapshot,
private state: RouterStateSnapshot,
private linkParam: string
) {}
resolve(): Observable<any> | Promise<any> | any {
return of(this.linkParam)
}
}
导出接口解析器WithParamModel{
决心(
路由:ActivatedRouteSnapshot,
状态:RouterStateSnapshot,
linkParam:string
):可观察的|承诺| T;
}
//自定义解析器
@可注射()
导出类ResolverWithParamsResolver实现了ResolverWithParamModel,它比答案中实现所需效果的代码段要复杂一些
注:
如果自定义解析器有10到15种可能的不同配置,我可能会创建10到15种解析器,因为从第一眼就很容易理解每个解析器的功能
免责声明:
不确定这是否是最好的解决方案,但我认为这是您想要的,如果您在实现过程中遇到任何问题,请创建一个stackblitz/codesandbox/plunker演示,我将尽力帮助您:)同样的想法,最好创建多个解析器。详细且易于理解,而且如果有一个路由/模块需要进行重大重构,您将仅更改该特定区域的解析器。我不确定这是否完全涵盖OP要求的内容。实际上,我在这里遗漏了一个关键点——如何在TeamComponent
中使用后续解析值。我试图订阅“activatedRoute.data”,但在导航到其他路由并返回后,订阅不再提供值。可能这是一个单独的问题-我将继续寻找其他问题,并可能编写我自己的问题。事实上,我刚刚发现正确的路由设置了activatedRoute。data
会发出新的解析值(可能通过advanceactivatedoute
从router state
查看这篇中等文章,它是如何使用解析器以及如何将组件作为子组件重用的一个很好的示例: