更新时间:2023-01-03 18:24:05
从 Angular 5.2 开始,您可以进行路由器配置以将所有参数继承到子状态.如果对血腥细节感兴趣,请参阅此提交,但它是如何为我工作的:
As of Angular 5.2, you can do Router configuration to inherit all params to child states. See this commit if interested in the gory details, but here's how it's working for me:
无论您在何处调用 RouterModule.forRoot()
,都包含一个配置对象,其继承策略设置为 always
(默认为 emptyOnly
>):
Wherever you have your call to RouterModule.forRoot()
, include a configuration object with the inheritance strategy set to always
(default is emptyOnly
):
import {RouterModule, ExtraOptions} from "@angular/router";
export const routingConfiguration: ExtraOptions = {
paramsInheritanceStrategy: 'always'
};
export const Routing = RouterModule.forRoot(routes, routingConfiguration);
现在,当您在子组件中查看 ActivatedRoute
时,祖先的参数会出现在那里(例如 activatedRoute.params
),而不是像 这样混乱的东西activateRoute.parent.parent.parent.params
.您可以直接访问该值(例如 activatedRoute.params.value.userId
)或通过 activatedRoute.params.subscribe(...)
订阅.
Now when you're in a child component looking at a ActivatedRoute
, ancestors' params appear there (e.g. activatedRoute.params
) rather than something messy like activatedRoute.parent.parent.parent.params
. You could access the value directly (e.g. activatedRoute.params.value.userId
) or subscribe via activatedRoute.params.subscribe(...)
.