Angular Route重用策略和查询参数
我正在使用 Angular 12,并且以下路由重用策略工作正常:
export class RoutingReuseStrategy implements RouteReuseStrategy {
handles: { [key: string]: DetachedRouteHandle } = {};
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return route.data.shouldReuse || false;
}
store(route: ActivatedRouteSnapshot, handle: {}): void {
if (route.data.shouldReuse) {
this.handles[route.routeConfig.path] = handle;
}
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!route.routeConfig && !!this.handles[route.routeConfig.path];
}
retrieve(route: ActivatedRouteSnapshot): {} {
if (!route.routeConfig) return null;
return this.handles[route.routeConfig.path];
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.data.shouldReuse || false;
}
}
在我重用的组件中,我订阅如下查询参数:
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.queryParams.subscribe(queryParams => {
// do something with queryParams
});
}
我的问题是,当首次加载组件时,此订阅仅触发一次。如果通过新的查询参数再次使用路由,则不会更新 ActivatedRoute。
有没有办法使用 RouteReuseStrategy 并且仍然能够在重用组件中订阅新的查询参数(或路由参数)?
我确实有一个使用路由器事件订阅的解决方法,它允许访问带有新参数的 URL。但如果有一种方法可以使用 queryParams 订阅,我想我更愿意这样做。
I'm using Angular 12, and I have the following route reuse strategy working fine:
export class RoutingReuseStrategy implements RouteReuseStrategy {
handles: { [key: string]: DetachedRouteHandle } = {};
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return route.data.shouldReuse || false;
}
store(route: ActivatedRouteSnapshot, handle: {}): void {
if (route.data.shouldReuse) {
this.handles[route.routeConfig.path] = handle;
}
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!route.routeConfig && !!this.handles[route.routeConfig.path];
}
retrieve(route: ActivatedRouteSnapshot): {} {
if (!route.routeConfig) return null;
return this.handles[route.routeConfig.path];
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.data.shouldReuse || false;
}
}
In my component that I'm reusing I subscribe to query parameters like this:
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.queryParams.subscribe(queryParams => {
// do something with queryParams
});
}
My problem is that this subscription only fires once, when the component is first loaded. The ActivatedRoute isn't updated if the route is used again with new query parameters.
Is there any way to use RouteReuseStrategy and still be able to subscribe to new query params (or route params) in the reused component?
I do have a workaround using a subscription to router events, which allows access to the URL with the new params in. But if there's a way to use the queryParams subscription I think I'd prefer to do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论