我使用的是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...
}
}
当我在寻找类似的解决方案时偶然发现了这个问题,但我不需要像完整的应用程序级路由或更多导入模块之类的东西。
下面的代码非常适合我使用,不需要额外的模块或导入。
GetParam(name){
const results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if(!results){
return 0;
}
return results[1] || 0;
}
PrintParams() {
console.log('param1 = ' + this.GetParam('param1'));
console.log('param2 = ' + this.GetParam('param2'));
}
http://localhost: 4200 / ? param1 = hello¶m2 = 123输出:
param1 = hello
param2 = 123
import { ParamMap, Router, ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
console.log(this.route.snapshot.queryParamMap);
}
更新
import { Router, RouterStateSnapshot } from '@angular/router';
export class LoginComponent {
constructor(private router: Router) {
const snapshot: RouterStateSnapshot = router.routerState.snapshot;
console.log(snapshot); // <-- hope it helps
}
}