Angular 2检查url中是否存在查询参数

ris*_*hal 15 angular2-routing angular

我需要检查当前url是否有查询字符串.

网址可以

http://localhost:4200/test?id=55555
Run Code Online (Sandbox Code Playgroud)

要么

http://localhost:4200/test
Run Code Online (Sandbox Code Playgroud)

我用过

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

但这只适用于网址中有id的情况.不知道如何检查它是否存在.

ran*_*al9 9

您可以在订阅功能中直接检查它,如下所示:

this.route.queryParams.subscribe((params)=> {
  //check lead Id here
  if(params['id']){
    console.log(params['id']);
  } else {
    console.log('id not found in params')
  }
});
Run Code Online (Sandbox Code Playgroud)


Ami*_*del 9

这是更好的解决方案,因为它订阅更改:

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


Muk*_*yuu 9

我会说使用:

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

就足够了。不要忘记private route: ActivatedRoute在构造函数中初始化 import { ActivatedRoute } from '@angular/router';

因为您只需要检查它是否存在。如果这样做,您的工作就会发生,例如添加一个布尔值以检查是否已设置。如果它不存在,那么将不会发生任何事情。然后,如果您需要在组件中的其他位置进行操作,则可以稍后检查布尔值是否为true / false,具体取决于您之前的设置方式。

  • 对于Angular 7:`this.route.snapshot.queryParamsMap.get('id')` (4认同)
  • @uihelp不确定我明白你的意思,但你可以检查:[Stackblitz演示](https://stackblitz.com/edit/angular-navigate-with-query-params-2ctiyy?file=src%2Fapp%2Fauthentication% 2Fauthentication.component.ts)和以下相关:/sf/ask/3506870741/,https:// stackoverflow.com/questions/51985973/in-angular-6-how-make-case-insensitive-url-pattern (2认同)