I need to check if the current url has query string.
url can be
http://localhost:4200/test?id=55555
or
http://localhost:4200/test
I have used
this.route.queryParams
.filter(params => 'id' in params)
.map(params => params.id)
.distinctUntilChanged()
.subscribe(
id=> {
//check lead Id here
console.log(id);
}
);
But this only works when there is id in the url. Not sure how to check if it exists.
I would say using:
ngOnInit() {
if (this.route.snapshot.queryParams['id']) {
//do your stuff. example: console.log('id: ', this.route.snapshot.queryParams['id']);
}
}
would be sufficient.
Don't forget to initialize private route: ActivatedRoute
in constructor and import { ActivatedRoute } from '@angular/router';
Since you only need to check if it exists or not. If it does your stuff would occur, like adding a boolean to check if it was set or not. If it does not exists then nothing would happen. Then if you need to do something somewhere else in the component you could check the boolean later if it was true/false depending on how you set it earlier.
For Angular 7 and 8, you would use
this.route.snapshot.queryParamMap.get('id')
You can directly check it inside your subscribe function like below :
this.route.queryParams.subscribe((params)=> {
//check lead Id here
if(params['id']){
console.log(params['id']);
} else {
console.log('id not found in params')
}
});
this is the better solution because it subscribes to changes :
this.route.queryParams.subscribe(
(params: Params) => {
if (params.hasOwnProperty('id')) { console.log(params['id']); }
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With