angular navigate to the same route with different parameter
In Angular 8, it is possible to load some other route and then return to the current active one. Just try this:
this.router.navigateByUrl('/', {skipLocationChange: true})
.then(()=>this.router.navigate(['editsingleuser',this.user.sub]));
Credits:
- How to reload the current route with the angular 2 router
- https://dev.to/oleksandr/mastering-angular-8-five-things-that-are-good-to-know-to-save-your-time-14hk (Item #5: #5. Reload component on same URL navigation)
The answer to this problem was that I had to subscribe to the route parameter in my EditSingleUser component, and use this value when I fetched the data for the page
In ngOnInit()
this.route.params
.switchMap((p: Params)=>{
let usr = p['username']; //read the username route parameter
return this.apiService.getUser(usr)} //call getUser with that parameter
)
.subscribe(data=> {
this.user= data
console.log("data :" + JSON.stringify(data));
this.setupFormData(); //use the resulting data to set up the form
})
As of 5.1, Angular has a setting for route reloading. It's a parameter called
onSameUrlNavigation
https://angular.io/api/router/ExtraOptions
@NgModule({
imports: [ RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' }) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
I suggest against using this technique though.
Angular's default behaviour does not reload the route when you navigate to the same route. It's a nice fail safe and it makes sense.
However, if you are changing the parameters, you could subscribe to the parameter change and act accordingly like this for example:
@Component({
selector: 'app-custom-edit',
templateUrl: './custom-edit.component.html',
styleUrls: ['./custom-edit.component.scss']
})
export class CustomEditComponent implements OnInit {
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe(res => {
if (+res.id === 0) this.initNew() // 'id' here is an example url parameter
else this.initExisting(+res.id)
})
}
initNew() {
//..
}
initExisting(id: number){
//..
}
}
And, by accordingly meaning, you could handle a set or reset of your component based on the parameter reality. Take it as your job, not the router's. This trigger will fire on the first initialization and when navigating to the same url with different parameters.
At the very least, it's more efficient than reloading the entire route.
I faced the same issue and this solved it in my case
constructor(private router: Router) {
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
}