Related to but not a duplicate of: How to keep query string parameters in URL when accessing a route of an Angular 2 app?
I have a very basic Angular app, and when I
The issue you are having is because you are calling
this.router.navigate(['/calculator'], navigationExtras);
inside your app component constructor or OnInit. Remember that queryParamMap is an observable, and so when you call navigate, the call will happen before your subscriber gets called. To fix your problem, just remove the navigate call. If you want your app component to autoredirect to calculator, the simplest safe method is to just change your paths to include:
routes: Routes = [
{path: '', redirectTo: 'calculator', pathMatch: 'full'},
...
]
There is a plunker that should illustrate this. To get routing in plunker working I used HashLocation strategy though, so make sure you use /#/...
when playing.
This should work.
constructor(
private router: Router,
private activatedRoute: ActivatedRoute
) { }
resetUrlQueryParams(){
this.router.navigate([],
{
relativeTo: this.activatedRoute,
queryParams: {}
});
}
if you want to retrieve query paramaters, then it is done using queryParam/queryParamMap..
this.route.queryParamMap.subscribe(params => {
console.log(params);
});
You may need to preserve the query parameters, or merge them as stated here.
https://angular.io/api/router/NavigationExtras
v4
preserveQueryParams: true
v5
queryParamsHandling: 'preserve'
You need to assign your query params to the queryParams Object.
Try:
this.router.navigate(['/calculator'], {queryParams: {a: 1}});
or add this to your navigation extras:
let navigationExtras: NavigationExtras = {
queryParamsHandling: 'preserve',
preserveFragment: true,
queryParams: {a:1}
};