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

当前回答

这对我很管用。我已经在路由模块中使用了子路由。


 this.route.firstChild.snapshot.paramMap.get('id');
   

其他回答

如果你没有使用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

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

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

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

当你有一个空路由对象时,这主要是因为你没有在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组件中使用的名称:)

刚刚偶然发现了同样的问题,这里的大多数答案似乎只解决了Angular内部路由的问题,然后其中一些解决了路由参数,这与请求参数不一样。

我猜我的用例与Lars最初的问题类似。

对我来说,用例是推荐跟踪:

Angular运行在mycoolpage.com上,使用散列路由,所以mycoolpage.com会重定向到mycoolpage.com/#/。然而,对于推荐,像mycoolpage.com?referrer=foo这样的链接也应该可用。不幸的是,Angular立即删除了请求参数,直接转到mycoolpage.com/#/。

任何一种使用空组件+ AuthGuard和获得queryParams或queryParamMap的“技巧”,不幸的是,对我不起作用。它们总是空的。

我的解决方案是在index.html中的一个小脚本中处理这个问题,该脚本获得完整的URL和请求参数。然后,我通过字符串操作获得请求参数值,并将其设置在窗口对象上。然后,一个单独的服务处理从窗口对象获取id。

index . html脚本

const paramIndex = window.location.href.indexOf('referrer=');
if (!window.myRef && paramIndex > 0) {
  let param = window.location.href.substring(paramIndex);
  param = param.split('&')[0];
  param = param.substr(param.indexOf('=')+1);
  window.myRef = param;
}

服务

declare var window: any;

@Injectable()
export class ReferrerService {

  getReferrerId() {
    if (window.myRef) {
      return window.myRef;
    }
    return null;
  }
}