I want to reload a page article/:id
every time a button is clicked, Angular is able to reload the page whenever the :id
changed, but if route to same :id
, then it ignores the changes.
export class DocumentComponent {
constructor(
private activatedRoute: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.routeSubscription = this.activatedRoute.params.subscribe(params => {
this.reloadPage(+params['id']);
});
}
clickReload(id: number) {
this.router.onSameUrlNavigation = 'reload';
this.router.navigate(['article', id]);
}
}
When the params changed, the observable params
will be triggered, and the reloadPage()
is executed. However, when I try to reload the same params
, Angular ignore it, how can I reload the same param
?
article/123 --> article/456 [ok]
article/111 --> article/222 [ok]
article/666 --> article/666 [not ok, how?]
I try to use the onSameUrlNavigation
, but it is not working... Am I doing something wrong?
You need to check the id if it is same then just reload the page. You can do like it:
clickReload(id: number) {
if(id == this.activatedRoute.snapshot.params.id) {
window.location.reload(); //if id is same then just reload the page
} else {
this.router.navigate(['article', id]);
}
}
You can just add as below and remove the validation.. just the navigation is enough.
@NgModule({
imports: [RouterModule.forRoot(routes, {
onSameUrlNavigation: 'reload',
enableTracing: false
})],
exports: [RouterModule]
})
example :
https://stackblitz.com/edit/mlc-onsameurlnavigation-activatedroute?file=app%2Fapp-routing.module.ts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With