我使用的是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...
  }
}

当前回答

你也可以使用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;
  }

其他回答

父组件从ActivatedRoute获取空参数

对我有用:

import {Component, OnDestroy, OnInit} from '@angular/core';
import { Router, ActivatedRoute, Params, RoutesRecognized } from '@angular/router';

@Component({
  selector: 'app-navigation-bar',
  templateUrl: './navigation-bar.component.html',
  styleUrls: ['./navigation-bar.component.scss']
})
export class NavigationBarComponent implements OnInit, OnDestroy {
  private sub: any;
  constructor(private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {
    this.sub = this.router.events.subscribe(val => {
      if (val instanceof RoutesRecognized) {
        console.log(val.state.root.firstChild.params);
      }
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

}

查询和路径参数(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);

在Angular 5中,查询参数是通过订阅this.route.queryParams来访问的(注意,后面的Angular版本推荐queryParamMap,也可以查看其他答案)。

例如:/应用程序吗?param1 = hallo&param2 = 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的router try, querystring。安装它

npm install --save querystring

对你的项目。在您的组件中执行如下操作

import * as qs from 'querystring';
...
ngOnInit() {
   const params = qs.parse(window.location.search.substring(1));
   ...
}

子字符串(1)是必要的,因为如果你有这样的'/mypage?Foo =bar'则键名为? Foo

它对我的作用是:

constructor(private route: ActivatedRoute) {}

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

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