6

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?

Boo Yan Jiong
  • 2,491
  • 5
  • 17
  • 31
  • 2
    Why exactly do you want it to reload BTW? `activatedRoute.params` is a BehaviorSubject which only pushes a new value when it has changed. Since there's no change in the `id` it won't trigger a change. – SiddAjmera Aug 29 '18 at 07:21
  • Possible duplicate of [How to reload the current route with the angular 2 router](https://stackoverflow.com/q/40983055/9775003) – Sanoj_V Aug 29 '18 at 07:28
  • Possible duplicate of [How to reload the current route with the angular 2 router](https://stackoverflow.com/questions/40983055/how-to-reload-the-current-route-with-the-angular-2-router) – Amit Chigadani Aug 29 '18 at 07:33

2 Answers2

3

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]);
    }
}
Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34
2

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

Shanil Arjuna
  • 1,135
  • 10
  • 18