【发布时间】:2018-05-07 10:24:11
【问题描述】:
我正在使用 Angular 5.0.3,我想使用一堆查询参数(如 /app?param1=hallo&param2=123)来启动我的应用程序。 How to get query params from url in Angular 2? 中给出的每个提示都对我不起作用。
知道如何让查询参数起作用吗?
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...
}
}
【问题讨论】:
-
你在使用路由器吗?网址来自哪里?
-
是的,有一个 ActivatedRoute。我更新了我的问题以显示我的主要组件的外观。
-
你能告诉我你的路线常数,你在哪里设置了所有路线吗?
-
const appRoutes: Routes = [ {path: "one", component: PageOneComponent}, {path: "", redirectTo: "/one", pathMatch: "full"}, {path: " **", redirectTo: "/one"} ];我的路线常数。我想将主应用程序中的所有参数存储在 DTO 中,然后导航到另一个页面。页面导航按预期工作,但我只能通过我的“getQueryParameter”函数在 main 处获取查询参数。我意识到在你的问题中存在我忘记的东西。我需要在任何地方标记我的参数名称吗?
-
是的,在您的路线中,您还需要定义参数。如果您查看 angular.io 上的路由文档,您可以看到它们如何在特定路由上定义参数。像这样 {path: 'abc/:param1', component: componentClassName}
标签: angular typescript angular-routing