I'd like to propose a different solution that uses both CustomRouteReuseStrategy
and onSameUrlNavigation
in order to force reload of the current route only when you need that behaviour and not always.
The solutions aims to forcing the reload of the current route by implementing a CustomRouteReuseStrategy
that checks for a particular queryParam
when requested to NOT reuse the current route explicitly. You can do that inside AppModule
like this:
import { ActivatedRouteSnapshot, BaseRouteReuseStrategy, RouteReuseStrategy, RouterModule } from '@angular/router';
class CustomRouteReuseStrategy extends BaseRouteReuseStrategy {
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return !future.queryParamMap.get('$forceReload') &&
(future.routeConfig === curr.routeConfig && isEqual(future.params, curr.params));
}
}
@NgModule({
// ... declarations and other module stuff
providers: [
{
provide: RouteReuseStrategy,
useClass: CustomRouteReuseStrategy
}
]
})
export class AppModule { }
Like shown in the code the shouldReuseRoute
checks whenever it can reuse the same route when both these conditions are true:
- There is no
$forceReload
(with any value) inside queryParams
- The current and future routeConfig are the same and share the same params (so in this case, with routes like this
/devices/:param
, /devices/1
is different from /devices/2
)
So, whenever you need to reload the current component, you can simply navigate like this:
const currentUrl = new URL(this.router.url, document.location.origin);
// set force reload query param
currentUrl.searchParams.set('$forceReload', 'true');
this.router.navigateByUrl(
// we can ignore URL origin and use only path and search
`${finalRedirectPath.pathname}${finalRedirectPath.search}`, {
onSameUrlNavigation: 'reload',
replaceUrl: true
}).then(
// then stuff
).catch(
// catch stuff
)
In this snippet we use URL constructor (that necessarily needs an origin to work) to set our $forceReload
param (and possibly preserves other query params) to a "truthy" value, the we navigate using only pathname and the resulting search string. The parameter onSameUrlNavigation: 'reload'
ensures that shouldReuseRoute
gets actually called always, the replaceUrl
replaces the current url in order to avoid stacking this new route inside the page history.