angular - 子组件初始化前如何获取参数
问题描述
通常的场景:用户看到 /login 窗口。他登录并被重定向到 /dashboard,他还可以在 /users 路径加载其他用户的列表。然后他点击一个用户并最终进入 /users/1 路径。所选用户的数据现在显示在屏幕上,因为它是与用户列表一起预加载的。
父组件是“/users” 子路径是“:userId”
不寻常但可能的情况:用户通过粘贴 url 直接进入 /users/1 路径(登录令牌仍然有效,因此他不需要登录)。
此时我们还没有加载用户列表,也没有选择用户的数据。
我使用路径解析器来加载用户列表。它在打开路径之前加载列表。问题出在 :userid 子路径上。我只能在子组件构造函数或 Init 方法中获取此参数。
这不好,因为每个具有子路径的组件都必须提取该参数并从列表中“选择”适当的用户。
我希望能够在一个地方选择用户。
我尝试为每个子路径创建单个解析器。此解析器尝试提取 :userid 参数,然后选择它。我还尝试将该解析器仅分配给父路径。我还尝试创建 CanActivate 保护,它应该提取:userid。
这些方法都不会产生任何结果,因为 route[.snapshot].paramMap 是空的。
我什至尝试订阅路由的 paramMap,但结果是一样的。
路由器文件
{ path: '/users', component: parentComponent, children: [
{ path: ':userid', component: userComponent, resolve: { user: SelectUserResolver } }
{ path: ':userid/edit', component: userEditComponent, resolve: { user: SelectUserResolver } }
{ path: ':userid/show, component: userShowComponent, resolve: { user: SelectUserResolver } }
..... many more paths .....
]
}
解析器文件
export class SelectUserResolver implement Resolve<any> {
constructor(private userService: UserService, private route: ActivatedRoute) {}
resolve() {
let userId = this.route.snaphot.paramMap.get('userid'); //<- empty map
this.userService.selectUser(userId);
}
}
父组件
export class parentComponent {
constructor(private route: ActivatedRoute) {
let userId = this.route.snapshot.paramMap.get('userid'); //<- empty map
}
}
用户组件
export class userComponent implements OnInit {
constructor(private route: ActivatedRoute) {}
ngOnInit() {
let userId = this.route.snapshot.paramMap.get('userid');// <- this works.
}
}
我希望 paramMap 有 userId,但无论我做什么,它都是空的。在子组件中访问它非常糟糕,因为我需要为创建的每个组件重复此代码。
解决方案
对于解析器,您不会注入ActivatedRoute
到构造函数中。根据文档:https ://angular.io/api/router/Resolve
当您实现时,Resolve<T>
您可以从方法中获取路由:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T
推荐阅读
- sql - SQL - 相乘的列未正确求和
- c - C 程序在执行 scanf() 并从用户那里获取输入后终止而没有任何错误
- react-native - 在反应原生的 Mapbox 上添加自定义表情符号
- c# - AWS Congito .NET Core JWT Lambda
- javascript - 通过将变量值与对象值匹配来创建变量?
- python - 在 facetplot 上绘制水平线(seaborn relplot)
- javascript - 根据错误状态代码重定向到 Angular 中的组件
- airflow - 无状态 Apache 气流服务
- python - 从一个目录中的所有 CSV 文件中获取具有特定 ID 的行,并创建一个仅包含具有该 ID 的记录的新 CSV 文件
- python - 仅通过电子邮件发送 for 循环中的特定值