gpt4 book ai didi

javascript - 为多种用途创建 Angular 解析器

转载 作者:太空狗 更新时间:2023-10-29 17:38:43 24 4
gpt4 key购买 nike

我正在寻找一种方法来使用一个 Angular 路线解析以用于我的所有路线,但具有不同的参数:

目前,我有类似的东西:

   {
path: 'user/:any',
component: UserprofileComponent,
resolve: { ProfiledUser: UserprofileResolver }
},

配置文件用户解析:

 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];

所以我的问题是,我是否应该像对权限保护那样使用解析器的原则?

例如:

  {
path: 'user/:any',
component: UserprofileComponent,
resolve: { ProfiledUser: UserprofileResolver }
data: {load: 'userprofile/admin'},
},

这是个好方法吗?如果是这样,我该怎么做才能使它最有效?

最佳答案

很好的问题,也让我挠了挠头:)。

那么让我们深入探讨我对这个问题的解决方案。

当使用 Resolver 时,我们可以用我们喜欢的任何东西(函数/类)替换解析器。

@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamComponent,
resolve: {
team: 'teamResolver'
}
}
])
],
providers: [
{
provide: 'teamResolver',
useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => 'team'
}
]
})

此片段直接来自 ng Docs

所以在你的情况下,你可以在 useValue 行中使用一些额外的参数,就像这样

useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) =>
new ResolverWithParamsResolver(
route,
state,
"customLink"
).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)
}
}

现在您可以访问您的linkParam

这是一个demo ,它比答案中的片段更复杂一些,实现了预期的效果。

注意事项:

如果自定义解析器有 10 到 15 种可能的不同配置,我可能会创建 10-15 个解析器,因为乍一看会更容易理解每​​个解析器的作用。

免责声明:

不确定这是否是最好的解决方案,但我认为这些是您想要的,如果您在实现过程中遇到任何问题,请创建一个 stackblitz/codesandbox/plunker 演示,我会尽力而为帮助你:)

关于javascript - 为多种用途创建 Angular 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55446725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com