如何从 Angular 5 中的 URL 获取查询参数? [英] How to get query parameters from URL in Angular 5?
问题描述
我使用的是 angular 5.0.3,我想用一堆查询参数来启动我的应用程序,比如 /app?param1=hallo¶m2=123
.如何从 Angular 2 中的 url 获取查询参数中给出的每个提示? 对我不起作用.
I'm using angular 5.0.3, I would like to start my application with a bunch of query parameters like /app?param1=hallo¶m2=123
. Every tip given in How to get query params from url in Angular 2? does not work for me.
任何想法如何获取查询参数?
Any ideas how to get query parameters work?
private getQueryParameter(key: string): string {
const parameters = new URLSearchParams(window.location.search);
return parameters.get(key);
}
这个私有函数帮助我获取参数,但我认为在新的 Angular 环境中这不是正确的方法.
This private function helps me to get my parameters, but I don't think it is the right way in new Angular environment.
[更新:]我的主应用程序看起来像
[update:] My main app looks like
@Component({...})
export class AppComponent implements OnInit {
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
// would like to get query parameters here...
// this.route...
}
}
推荐答案
在 Angular 5 中,查询参数是通过订阅 this.route.queryParams
来访问的(注意以后的 Angular 版本 recommend queryParamMap
,另见其他答案.
In Angular 5, the query params are accessed by subscribing to this.route.queryParams
(note that later Angular versions recommend queryParamMap
, see also other answers).
示例:/app?param1=hallo¶m2=123
param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
console.log('Called Constructor');
this.route.queryParams.subscribe(params => {
this.param1 = params['param1'];
this.param2 = params['param2'];
});
}
然而,路径变量由 this.route.snapshot.params
示例:/param1/:param1/param2/:param2
param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
this.param1 = this.route.snapshot.params.param1;
this.param2 = this.route.snapshot.params.param2;
}
这篇关于如何从 Angular 5 中的 URL 获取查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!