Angular 2 Check if query parameter exists in the url

淺唱寂寞╮ 提交于 2019-12-23 06:57:02

问题


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:


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.




回答2:


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



回答3:


this is the easy way :

this.route.queryParams.subscribe(
    (params: Params) => {
        if (params.hasOwnProperty('id')) { console.log(params['id']); }
    }
);



回答4:


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.




回答5:


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");
      }
    });
  }



回答6:


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



来源:https://stackoverflow.com/questions/41562267/angular-2-check-if-query-parameter-exists-in-the-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!