首页 > 解决方案 > 子组件初始化前如何获取参数

问题描述

通常的场景:用户看到 /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,但无论我做什么,它都是空的。在子组件中访问它非常糟糕,因为我需要为创建的每个组件重复此代码。

标签: angular

解决方案


对于解析器,您不会注入ActivatedRoute到构造函数中。根据文档:https ://angular.io/api/router/Resolve

当您实现时,Resolve<T>您可以从方法中获取路由:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T

推荐阅读