角度2检查网址中是否存在查询参数 [英] Angular 2 Check if query parameter exists in the url

查看:64
本文介绍了角度2检查网址中是否存在查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查当前网址是否具有查询字符串.

I need to check if the current url has query string.

网址可以是

http://localhost:4200/test?id=55555

http://localhost:4200/test

我用过

this.route.queryParams
     .filter(params => 'id' in params)
     .map(params => params.id)
     .distinctUntilChanged()
     .subscribe(
     id=> {
                //check lead Id here
                console.log(id);
            }
     );

但这仅在URL中有ID时有效.不知道如何检查它是否存在.

But this only works when there is id in the url. Not sure how to check if it exists.

推荐答案

我会说使用:

ngOnInit() {
 if (this.route.snapshot.queryParams['id']) {
      //do your stuff. example: console.log('id: ', this.route.snapshot.queryParams['id']);
 }
}

就足够了.

不要忘记在构造函数和import { ActivatedRoute } from '@angular/router';

Don't forget to initialize private route: ActivatedRoute in constructor and import { ActivatedRoute } from '@angular/router';

因为您只需要检查它是否存在.如果这样做,您的东西就会发生,就像添加一个布尔值以检查它是否被设置.如果它不存在,那么将不会发生任何事情.然后,如果您需要在组件中的其他地方做一些事情,您可以稍后检查 boolean 是否为true/false,这取决于您之前的设置方式.

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.

对于Angular 7和Angular 8,您将使用 this.route.snapshot.queryParamMap.get('id')

For Angular 7 and 8, you would use this.route.snapshot.queryParamMap.get('id')

这篇关于角度2检查网址中是否存在查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆