Angular - 如何仅在 child 路由激活时订阅 child 路由参数
Angular - How to subscribe to child route params only when the child route is activated
我有分屏设计。我只想在激活 child 路由时从 parent 路由访问文件夹 ID。下面的代码可以为我获取正确的参数,但是在我只显示 parent 路由的初始加载中,我收到控制台错误:
Cannot read property 'params' of null
this.activatedRoute.firstChild.params.subscribe((urlParameters) => {
this.folder_id = urlParameters['folderId'];
});
有没有办法只在 child 激活后才激活上述内容?
你可以试试
if(this.activatedRoute.firstChild)
this.activatedRoute.firstChild.params.subscribe((urlParameters) => {
this.folder_id= urlParameters['folderId'];
});
你可以订阅routeParams的变化,但是只有当child存在并且有你需要的时候才会触发。 ABOSes 版本将无法运行,因为没有 firstChild 将无法进行订阅,因此当您实际导航到 firstChild 时,不会触发订阅。
我的版本将创建订阅,这将过滤有效事件。请注意,这很可能是更好的方法:
this.route.params.subscribe(() => {
if (this.route.firstChild && this.route.firstChild.snapshot.params['folderId']) {
this.folderId = +this.route.firstChild.snapshot.params['folderId'];
}
});
我有分屏设计。我只想在激活 child 路由时从 parent 路由访问文件夹 ID。下面的代码可以为我获取正确的参数,但是在我只显示 parent 路由的初始加载中,我收到控制台错误:
Cannot read property 'params' of null
this.activatedRoute.firstChild.params.subscribe((urlParameters) => {
this.folder_id = urlParameters['folderId'];
});
有没有办法只在 child 激活后才激活上述内容?
你可以试试
if(this.activatedRoute.firstChild)
this.activatedRoute.firstChild.params.subscribe((urlParameters) => {
this.folder_id= urlParameters['folderId'];
});
你可以订阅routeParams的变化,但是只有当child存在并且有你需要的时候才会触发。 ABOSes 版本将无法运行,因为没有 firstChild 将无法进行订阅,因此当您实际导航到 firstChild 时,不会触发订阅。
我的版本将创建订阅,这将过滤有效事件。请注意,这很可能是更好的方法:
this.route.params.subscribe(() => {
if (this.route.firstChild && this.route.firstChild.snapshot.params['folderId']) {
this.folderId = +this.route.firstChild.snapshot.params['folderId'];
}
});