26

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.

1

6 Answers 6

27

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

4
15

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')
  }
});
2
  • 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, 2017 at 6:24
  • 1
    You can use if( params.hasOwnPrperty('id') ) or if( Object.keys(params).indexOf('id') !== -1 ) instead of if(params['id']) Jan 10, 2017 at 6: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']); }
    }
);
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.

1
  • what's the point of having the id key in the url but not the value? Far fetched to me..
    – jpgrassi
    Dec 12, 2017 at 8:31
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");
      }
    });
  }
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.