我使用的是angular 5.0.3,我想用一堆查询参数启动我的应用程序,比如/app?param1=hallo&param2=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...
  }
}

当前回答

最好的解决方案是使用ActivatedRoute:

    constructor(private route: ActivatedRoute) {}
    
    ngOnInit(): void {
        this.route.queryParams.subscribe((params) => {
         console.log(params);
         const queryparams = params['queryName'];
        });
    }

其他回答

当你有一个空路由对象时,这主要是因为你没有在app.component.html中使用路由器出口。

如果没有这个,你将无法获得一个有意义的非空子对象的路由对象,特别是params和queryParams。

尝试添加<router-outlet><router-outlet> < app-main-component > < / app-main-component >

在此之前,确保你在App -routing >中准备好了查询参数,它导出了App组件使用的类Route:

param: '/param/:dynamicParam', path: MyMainComponent

当然,最后一件事,为了获得你的参数,我个人使用this.route.snapshot.params.dynamicParam,其中dynamicParam是在你的app-routing组件中使用的名称:)

它对我的作用是:

constructor(private route: ActivatedRoute) {}

ngOnInit()
{
    this.route.queryParams.subscribe(map => map);
    this.route.snapshot.queryParams; 
}

如何在angular2中从url获取查询参数?

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
    }
}

你也可以使用HttpParams,比如:

  getParamValueQueryString( paramName ) {
    const url = window.location.href;
    let paramValue;
    if (url.includes('?')) {
      const httpParams = new HttpParams({ fromString: url.split('?')[1] });
      paramValue = httpParams.get(paramName);
    }
    return paramValue;
  }

查询和路径参数(Angular 8)

url,如https://myapp.com/user/666/read?age=23使用

import { combineLatest } from 'rxjs';
// ...

combineLatest( [this.route.paramMap, this.route.queryParamMap] )
  .subscribe( ([pathParams, queryParams]) => {
    let userId = pathParams.get('userId');    // =666
    let age    = queryParams.get('age');      // =23
    // ...
  })

更新

如果你使用this.router.navigate([someUrl]);你的查询参数被嵌入到someUrl字符串中,然后angular对URL进行编码,你会得到类似https://myapp.com/user/666/read%3Fage%323的东西——以上解决方案会给出错误的结果(queryParams将为空,路径参数可以粘在最后一个路径参数上,如果它在路径端)。在这种情况下,改变导航的方式

this.router.navigateByUrl(someUrl);