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

当前回答

Angular路由器提供了parseUrl(url: string)方法,用于将url解析为UrlTree。UrlTree的一个属性是queryParams。所以你可以这样做:

this.router.parseUrl(this.router.url).queryParams[key] || '';

其他回答

我知道OP要求的是Angular 5的解决方案,但对于所有在更新的(6+)Angular版本中偶然遇到这个问题的人来说。引用文档,关于ActivatedRoute。queryParams(大多数其他答案都基于queryParams):

两处较老的房产仍在出售。他们的能力不如 它们的替代品是不鼓励的,将来可能会被弃用 角的版本。 params -一个包含required和optional的Observable 指定路由的参数。请改用paramMap。 queryParams -一个包含可用查询参数的可观察对象 所有路线。请改用queryParamMap。

根据文档,获取查询参数的简单方法是这样的:

constructor(private route: ActivatedRoute) { }

ngOnInit() {
    this.param1 = this.route.snapshot.paramMap.get('param1');
    this.param2 = this.route.snapshot.paramMap.get('param2');
}

要了解更高级的方法(例如,高级组件重用),请参阅本文档章节。

编辑:

正如下面评论中正确指出的那样,这个答案是错误的——至少对于OP指定的情况是如此。

OP请求获取全局查询参数(/app?param1=hallo&param2=123);在这种情况下,您应该使用queryParamMap(就像@dapperdan1985 answer一样)。

另一方面,paramMap用于特定于路由的参数(例如/app/:param1/:param2,导致/app/hallo/123)。

感谢@JasonRoyle和@daka指出这一点。

在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的最新版本中,其他答案中建议你可以使用ActivatedRoute injectable,特别是使用snapshot属性,轻松获取查询参数:

this.route.snapshot.queryParamMap.get('param')

或者订阅属性(在查询字符串会更新的情况下使用,例如通过用户id导航):

this.route.queryParamMap.subscribe(params => console.log(params));

我在这里告诉你,这些解决方案有一个巨大的缺陷,一段时间没有得到解决:https://github.com/angular/angular/issues/12157

总而言之,唯一的防弹解决方案是使用优秀的老香草javascript。在本例中,我为URL操作创建了一个服务:

import { Injectable } from '@angular/core';
import { IUrl } from './iurl';

@Injectable()
export class UrlService {
    static parseQuery(url: string): IUrl {
        const query = url.slice(url.indexOf('?')+1).split('&').reduce( (acc,query) => {
            const parts = query.split('=');
            acc[parts[0]] = parts[1];
            return acc;
        }, {});

        return {
            a: query['a'],
            b: query['b'],
            c: query['c'],
            d: query['d'],
            e: query['e']
        }
    }
}

这对我来说是最干净的解决方案

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');
  }
}

父组件从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();
  }

}