29

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.

rishal
  • 3,230
  • 3
  • 22
  • 29

6 Answers6

31

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

Mukyuu
  • 6,436
  • 8
  • 40
  • 59
  • 6
    for Angular 7: `this.route.snapshot.queryParamsMap.get('id')` – Juan José Ramírez Mar 14 '19 at 18:19
  • this will check only 'id' what if there's 'ID' or 'Id', is there any way where we can check in all cases ? – uihelp Jul 02 '19 at 01:38
  • 2
    @uihelp Not sure I understand what you mean, but you can check: [Stackblitz Demo](https://stackblitz.com/edit/angular-navigate-with-query-params-2ctiyy?file=src%2Fapp%2Fauthentication%2Fauthentication.component.ts) and following related: https://stackoverflow.com/questions/50098153/how-to-take-the-values-from-the-case-sensitive-query-param-variables, https://stackoverflow.com/questions/51985973/in-angular-6-how-make-case-insensitive-url-pattern – Mukyuu Jul 03 '19 at 02:05
  • For Angular 10+ you need to use `this._route.snapshot.queryParamMap.has('param_name')` to check if a query param exists, otherwise the `.get` method will give you an error – Alex Christodoulou May 06 '21 at 08:06
16

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')
  }
});
ranakrunal9
  • 13,320
  • 3
  • 42
  • 43
  • issue with this is when i first load the page I will get `id not found in params` then the value of `id`. – rishal Jan 10 '17 at 06:24
  • 1
    You can use `if( params.hasOwnPrperty('id') )` or `if( Object.keys(params).indexOf('id') !== -1 )` instead of `if(params['id'])` – ranakrunal9 Jan 10 '17 at 06:30
9

this is the better solution because it subscribes to changes :

this.route.queryParams.subscribe(
    (params: Params) => {
        if (params.hasOwnProperty('id')) { console.log(params['id']); }
    }
);
Amin Adel
  • 970
  • 3
  • 17
  • 33
0

Preliminary

When one subscribes to queryParams like below, the params variable holds an object where the keys are all the query paramaters and the value can either be a single value or an array of values. One can do a console.log(params); to check this result. For example:

when url is: http://example.com/?lion=10&lion=15&cat=20

and we then try to see what params holds:

this.route.queryParams.subscribe((params) => {
    console.log(params);
});

the result would be an object where keys are lion and cat but values are an array for lion since it has two occurrences and for cat is a single value:

{ lion: [10, 15], cat:20 }

Now answering the question

Let's take the url to be: http://example.com/?id&name=james

One can notice that there is no value for id. It is possible that a url just has a key but no value and yet we would like to know that the key at least is present. If we were to do:

if(params['id']){
    // do something
}

this condition will return false even though the key id is present. We might actually want to do something when the key alone is present and something else when the key and value are present. In that case we can use lodash library to effectively sort key and key/value results. After importing lodash library in to the project. One can use _.has to do this:

// check if id key is present in params object first
if(_.has(params, 'id')) {
    if(params['id']=="") {
      // id key is present but has no value so do something
    } else {
      // id key is present and has a value as well so do something else
    }
} else {
    // since id key itself is not present do something totally different here
}

Of course the above code assumes that id key appears only once in the url params. Otherwise, one would have to loop through an array and check each value.

Adam Ranganathan
  • 1,691
  • 1
  • 17
  • 25
0

I assume you use the Angular Routing System here. Then inject the current activated route in the constructor of your component like so:

constructor(private activatedRoute: ActivatedRoute)

Then check in i.e. your ngOnInit() like so:

ngOnInit() {
    console.log("Hello ngOnInit");
    let token = null;
    this.activatedRoute.queryParamMap.subscribe((next : ParamMap) => {
      token = next.get("token")

      if (token) {
        console.log(token);
      } else {
        console.log("no token given in url");
      }
    });
  }
Rainer Feike
  • 191
  • 1
  • 9
0

Since no one mentioned the usage of snapshot I'm providing my answer with it. If you don't actually need an observable, meaning the url is modified once (e.g user navigates to edit page) you can take advantage of the Snapshot alternative which is much more succinct. So, in your app you could do:

constructor(private route: ActivatedRoute) {

}

ngOnInit(): void { 
    if (this.route.snapshot.params['id']) {
        // id exists, so do something with it.

    }
}

But take in mind this point:

Remember: you only get the initial value of the parameter map with this technique. Stick with the observable paramMap approach if there's even a chance that the router could re-use the component. This sample stays with the observable paramMap strategy just in case.

Source: Snapshot: the no-observable alternative

jpgrassi
  • 5,482
  • 2
  • 36
  • 55