Reputation: 4596
I have below config
{ path:'test/display/:mode' ,component:DisplayComponent }
This is working if i call like
test/display/5
But it not able to find matching route when i give
test/display/?mode=5
I am not able to figure how to make it
Please help Thanks
Upvotes: 2
Views: 4812
Reputation: 2557
You have to define your routes differently (auxilary) for both the options:
const routes: Routes = [
{ path: 'test/:mode', component: TestComponent }, // for path variables
{ path: 'test', component: TestComponent } // for query params
];
For the first one your url will look like:
http://localhost:4200/test/20
and for the second one:
http://localhost:4200/test?mode=20
And then use queryParams
to read the values:
constructor(private route: ActivatedRoute) {
this.route.queryParams.subscribe(params => {
console.log(params['mode']);
});
}
Upvotes: 1
Reputation: 23
The route specifies that it must have a mode parameter on the end, so the alternative form without a mode parameter at the end of the path, is different.
{ path:'test/display/:mode' ,component:DisplayComponent }
if different to:
{ path:'test/display/' ,component:DisplayComponent }
The query string is not part of the route at all, so adding one is not the equivalent of ":mode".
So, you simply need to specify both of these alternative routes if you want to support route parameters and query strings. Generally it's best practice to use route parameters only for required parameters such as the id of a resource you are requesting/updating. Query string parameters are best used for optional parameters, such as search options, data windowing, or algorithm tweaks.
[{ path:'test/display/:mode' ,component:DisplayComponent },
{ path:'test/display/' ,component:DisplayComponent }]
is what you want. Then you can
test/display/5
and
test/display/?mode=5
To obtain the query string value you need to subscribe to the queryParams of the activatedRoute service.
import { Component, OnInit} from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
export class ExampleComponent implements OnInit {
public mode = null;
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.activatedRoute.queryParams.subscribe((qp: Params) => {
this.mode = qp['mode'];
});
}
}
Upvotes: 0
Reputation: 3089
Try this way
constructor(private route: ActivatedRoute) { }
ngOnInit() {
if(this.route.snapshot.paramMap.get('mode')){
// if mode
}else {
// if not mode
}
}
{ path:'test/display' ,component:DisplayComponent }
Upvotes: 0
Reputation: 350
This is indeed not the same, declaring :mode in your router config tells Angular that you are declaring an angular route parameter, by setting ?mode=5 in the url you are declaring a query parameter. These are handled differently.
Good stackoverflow article on how to use query parameter: How to get query parameters from URL in Angular 5?
Upvotes: 0