如何在 Angular 5 中从 URL 中获取查询参数?
如何在 Angular 5 中从 URL 中获取查询参数?
我正在使用angular 5.0.3,我想要使用一系列查询参数来启动我的应用程序,例如/app?param1=hallo¶m2=123
。在Angular 2中如何从URL获取查询参数?中提供的任何提示都对我不起作用。
有什么想法可以使查询参数起作用吗?
private getQueryParameter(key: string): string { const parameters = new URLSearchParams(window.location.search); return parameters.get(key); }
这个私有函数帮助我获取我的参数,但我不认为这是在新的Angular环境中的正确方式。
[更新:]
我的主要应用程序如下:
@Component({...}) export class AppComponent implements OnInit { constructor(private route: ActivatedRoute) {} ngOnInit(): void { // would like to get query parameters here... // this.route... } }
admin 更改状态以发布 2023年5月25日
这对我来说是最干净的解决方案
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; export class MyComponent { constructor( private route: ActivatedRoute ) {} ngOnInit() { const firstParam: string = this.route.snapshot.queryParamMap.get('firstParamKey'); const secondParam: string = this.route.snapshot.queryParamMap.get('secondParamKey'); } }