I have a newly created Angular 14 application. I've created a simple component called TestComponent.
Inside the routing.module.ts I've specified the following Route:
const routes: Routes = [{ path:'test', component: TestComponent }]
The problem occurs when I try to navigate to this component passing some query params like this:
http://mysite:80/test?param=teststring
The component is loaded without problems, but no query params is retrieved. It's the same situation if typed http://mysite:80/test
As far as I understand from the documentation, this url should be valid and by accessing params with
this.route.queryParamMap.subscribe(params => {
let myparam = params.get('param');
});
this.route is an ActivatedRoute object, injected inside the constructor of the component
I should be able to get the value, but I keep getting null. Since it's a query parameter, it's optional and so the route specified inside the routing.module.ts should be correct.
Any idea on how I can solve it?
CodePudding user response:
Try this syntax here, using :test
in your case: https://angular-training-guide.rangle.io/routing/routeparams
example:
export const routes: Routes = [
{ path: '', redirectTo: 'product-list', pathMatch: 'full' },
{ path: 'product-list', component: ProductList },
{ path: 'product-details/:id', component: ProductDetails }
];
URL: localhost:3000/product-details/5
CodePudding user response:
The query parameters are initially empty or does not load the values first because the components loads before the actual routings are applied.
Solution 1
Wait for the navigation to end using event property NavigationEnd
constructor(private route: ActivatedRoute, private router:Router) { }
ngOnInit(): void {
this.router.events.subscribe(
(event: RouterEvent) => {
if (event instanceof NavigationEnd) {
this.route.queryParamMap.subscribe(params => { //You may also use simply route.params as well instead of qureyParamMap
let myparam = params.get('param');
});
}
})
}
Solution 2
Another approach could be adding a delay,say .10s to the subscription. Try avoiding this approach unless and until you have a pre requirement of some kind of delay on pageload.
ngOnInit(): void {
setTimeout(() => {
this.route.queryParamMap.subscribe(params => {
let myparam = params.get('param');
});
}, 10);//A dealy of 10ms is provided here
}
Hope it helps!