Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Check if query parameter exists in the url

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.

like image 218
rishal Avatar asked Jan 10 '17 06:01

rishal


3 Answers

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')

like image 174
Mukyuu Avatar answered Oct 18 '22 18:10

Mukyuu


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')
  }
});
like image 37
ranakrunal9 Avatar answered Oct 18 '22 18:10

ranakrunal9


this is the better solution because it subscribes to changes :

this.route.queryParams.subscribe(
    (params: Params) => {
        if (params.hasOwnProperty('id')) { console.log(params['id']); }
    }
);
like image 9
Amin Adel Avatar answered Oct 18 '22 19:10

Amin Adel