Angular – Reload a component with different route parameters in angular4

angularangular-routerangular-routing

I am using angular2 routing. When the user re-enters the value in the search field and clicks on search, the same component needs to be reloaded but with different route parameters.

<button (click)="onReload()">Search</button>

onReload() {
this.router.navigate(['results',this.location]);
}

This is my route path for my ResultsComponent

{ path:'results/:location', component:ResultsComponent}

This function changes the URL, but it does not reinitialize the component.

In angularjs, ui-router I could achieve it like this.

$state.go($state.current, location, {reload: true});

How do I do this in angular4?

Best Answer

You need to perform the initialization logic within the subscription call back function within the subscription call back function of the route.params observable stream.

In your component class

@Component({
  ...
})
export class MyComponent implements OnInit {

   myLocation:string;

   constructor(private route:ActivatedRoute) {}

   ngOnInit() {
     this.route.params.subscribe((params:Params) => {
        this.myLocation = params['location'];
        // -- Initialization code -- 
        this.doMyCustomInitialization();
     }
   }

   private doMyCustomInitialization() {
       console.log(`Reinitializing with new location value ${this.location}`);
   }
}

On a different note, if you need to resolve data based on the value of 'location' you should use a resolve guard which resolves the data before the component is created. See https://angular.io/guide/router#resolve-guard for more information regarding resolve guards and routing.

Here's a working plunkr. https://plnkr.co/edit/g2tCnJ?p=preview