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的情况.不知道如何检查它是否存在.
您可以在订阅功能中直接检查它,如下所示:
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)
这是更好的解决方案,因为它订阅更改:
this.route.queryParams.subscribe(
(params: Params) => {
if (params.hasOwnProperty('id')) { console.log(params['id']); }
}
);
Run Code Online (Sandbox Code Playgroud)
我会说使用:
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,具体取决于您之前的设置方式。
| 归档时间: |
|
| 查看次数: |
20670 次 |
| 最近记录: |