Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular not reload if route to same param

Tags:

angular

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?

like image 334
Boo Yan Jiong Avatar asked Aug 29 '18 07:08

Boo Yan Jiong


2 Answers

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]);
    }
}
like image 144
Rohit Sharma Avatar answered Oct 07 '22 11:10

Rohit Sharma


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

like image 20
Shanil Arjuna Avatar answered Oct 07 '22 12:10

Shanil Arjuna