routes – How to Refresh a Component in Angular

routes – How to Refresh a Component in Angular

After some research and modifying my code as below, the script worked for me. I just added the condition:

this.router.navigateByUrl(/RefreshComponent, { skipLocationChange: true }).then(() => {
    this.router.navigate([Your actualComponent]);
}); 

Use the this.ngOnInit(); to reload the same component instead reloading the entire page!!

DeleteEmployee(id:number)
  {
    this.employeeService.deleteEmployee(id)
    .subscribe( 
      (data) =>{
        console.log(data);

        this.ngOnInit();

      }),
      err => {
        console.log(Error);
      }   
  }

routes – How to Refresh a Component in Angular

Adding this to code to the required components constructor worked for me.

this.router.routeReuseStrategy.shouldReuseRoute = function () {
  return false;
};

this.mySubscription = this.router.events.subscribe((event) => {
  if (event instanceof NavigationEnd) {
    // Trick the Router into believing its last link wasnt previously loaded
    this.router.navigated = false;
  }
});

Make sure to unsubscribe from this mySubscription in ngOnDestroy().

ngOnDestroy() {
  if (this.mySubscription) {
    this.mySubscription.unsubscribe();
  }
}

Refer to this thread for more details – https://github.com/angular/angular/issues/13831

Leave a Reply

Your email address will not be published.