如何从angular-5中的url获取查询参数?

Lar*_*ars 136 typescript angular-routing angular

我正在使用angular 5.0.3,我想用一堆查询参数启动我的应用程序.比如"/ app?param1 = hallo¶m2 = 123".在如何从angular2中的url获取查询参数中给出的每个提示不适合我.

任何想法如何获取查询参数的工作?

private getQueryParameter(key: string): string {
  const parameters = new URLSearchParams(window.location.search);
  return parameters.get(key);
}
Run Code Online (Sandbox Code Playgroud)

这个私有函数可以帮助我获取参数,但我不认为它是新Angular环境中的正确方法.

[更新:]我的主应用程序看起来像@Component({...})导出类AppComponent实现OnInit {

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    // would like to get query parameters here...
    // this.route...
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 186

在Angular 5中,通过订阅this.route.queryParams来访问查询参数.

示例:"/ app?param1 = hallo¶m2 = 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'];
    });
}
Run Code Online (Sandbox Code Playgroud)

而,路径变量由"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;
}
Run Code Online (Sandbox Code Playgroud)

  • 只是添加一个点,使用ngOnInit而不是构造函数. (21认同)
  • 根据Angular 6 [docs](https://angular.io/guide/router#activated-route),不鼓励使用ActivatedRoute.queryParams和.params,在将来的版本中可能会弃用它们.见更新[here](/sf/answers/3626597761/) (11认同)

dap*_*985 89

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

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');
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这在 Angular8 中对我有用。this.route.snapshot.queryParamMap 有效。this.route.snapshot.paramMap 对我不起作用。 (2认同)
  • @RomeoProfijt ```paramMap``` 用于路由中的参数,而不是查询参数。如果你有一个定义为``/myroute/:id```的路由并导航到````/myroute/45````那么你可以从````paramMap.get('id')``获得45 `。 (2认同)

grr*_*enn 74

我知道OP要求Angular 5解决方案,但是对于那些因为更新(6+)Angular版本而遇到这个问题的所有人而言.引用文档,关于ActivatedRoute.queryParams(大多数其他答案基于):

还有两个较旧的房产.他们的能力低于他们的替代者,气馁,并且可能在未来的Angular版本中被弃用.

params - 一个Observable,包含特定于路由的必需参数和可选参数.请改用paramMap.

queryParams - 包含可用于所有路由的查询参数的Observable.请改用queryParamMap.

根据文档,获取查询参数的简单方法如下所示:

constructor(private route: ActivatedRoute) { }

ngOnInit() {
    this.param1 = this.route.snapshot.paramMap.get('param1');
    this.param2 = this.route.snapshot.paramMap.get('param2');
}
Run Code Online (Sandbox Code Playgroud)

有关更高级的方法(例如高级组件重用),请参阅文档的章节.

  • 这不应该使用queryParamMap而不是paramMap来获取查询字符串参数吗? (7认同)
  • @JasonRoyle看来您是正确的,`paramMap`不起作用。 (2认同)

Kam*_*ski 21

查询和路径参数(Angular 8)

对于像https://myapp.com/user/666/read?age=23这样的 url使用

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
    // ...
  })
Run Code Online (Sandbox Code Playgroud)

更新

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

this.router.navigateByUrl(someUrl);
Run Code Online (Sandbox Code Playgroud)

  • 感谢@Kamil Kiełczewski,你拯救了我的一天 (2认同)

a5t*_*tr0 11

您还可以使用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;
  }
Run Code Online (Sandbox Code Playgroud)


izi*_*k f 10

它的工作对我来说:

constructor(private route: ActivatedRoute) {}

ngOnInit()
{
    this.route.queryParams.subscribe(map => map);
    this.route.snapshot.queryParams; 
}
Run Code Online (Sandbox Code Playgroud)

查看更多选项如何从angular2中的url获取查询参数?


Dmi*_*nko 8

import { ParamMap, Router, ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {}

ngOnInit() {
    console.log(this.route.snapshot.queryParamMap);
}
Run Code Online (Sandbox Code Playgroud)

UPDATE

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这似乎是不够的,我得到ActivatedRouteSnapshot但queryParams是一个空对象,params也是空的.queryParamMap.get('name')返回null.看来ngOnInit()得到这样的查询参数还为时过早. (5认同)

Don*_*ato 8

不幸的是,最干净的解决方案并不是最具扩展性的解决方案。在 Angular 的最新版本中,在其他答案中建议您可以使用 ActivatedRoute Injectible 轻松获取查询参数,并特别使用快照属性:

this.route.snapshot.queryParamMap.get('param')
Run Code Online (Sandbox Code Playgroud)

或 subscribe 属性(在查询字符串将更新的情况下使用,例如通过用户 ID 导航):

this.route.queryParamMap.subscribe(params => console.log(params));
Run Code Online (Sandbox Code Playgroud)

我在这里告诉你,这些解决方案有一个已经有一段时间没有解决的巨大缺陷: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']
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ada*_*lak 8

Angular Router provides method parseUrl(url: string) that parses url into UrlTree. One of the properties of UrlTree are queryParams. So you can do sth like:

this.router.parseUrl(this.router.url).queryParams[key] || '';
Run Code Online (Sandbox Code Playgroud)

  • 如果您不需要处理 URL 更改,即参数已在当前 URL 中可用,请使用此选项。否则就以可观察的方式去做。 (2认同)

Ree*_*eed 6

当我在寻找类似的解决方案时偶然发现了这个问题,但我不需要像完整的应用程序级路由或更多导入的模块之类的东西。

以下代码非常适合我使用,不需要额外的模块或导入。

  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'));
  }
Run Code Online (Sandbox Code Playgroud)

http://localhost:4200/?param1=hello&param2=123 输出:

param1 = hello
param2 = 123
Run Code Online (Sandbox Code Playgroud)