Angular RouteReuseStrategy and queryParams

416 Views Asked by At

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.

0

There are 0 best solutions below