首页 文章

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

提问于
浏览
54

我正在使用angular 5.0.3,我想用一堆查询参数启动我的应用程序 . 喜欢"/app?param1=hallo&param2=123" . How get query params from url in angular2?中给出的每个提示都不适合我 .

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

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

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

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

constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    // would like to get query parameters here...
    // this.route...
  }
}

11 回答

  • 22

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

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

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

    示例:“/ app?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;
    }
    
  • 102

    我知道OP要求Angular 5解决方案,但是对于那些偶然发现这个更新(6)Angular版本的人而言 . 引用Docs,关于ActivatedRoute.queryParams(大多数其他答案都基于):

    仍然有两个较旧的房产 . 他们的能力低于他们的替代品,气馁,并且可能在未来的Angular版本中被弃用 . params - 包含特定于路径的必需和可选参数的Observable . 请改用paramMap . queryParams - 包含可用于所有路由的查询参数的Observable . 请改用queryParamMap .

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

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

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

  • 0

    它的工作对我来说:

    constructor(private route: ActivatedRoute) {}
    
    ngOnInit()
    {
        this.route.queryParams.subscribe(map => map);
        this.route.snapshot.queryParams; 
    }
    

    看看更多选项How get query params from url in angular2?

  • 0
    import { ParamMap, Router, ActivatedRoute } from '@angular/router';
    
    constructor(private route: ActivatedRoute) {}
    
    ngOnInit() {
        console.log(this.route.snapshot.queryParamMap);
    }
    

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

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

    如果没有这个,您将无法获得具有非空子对象的有意义的路由对象,尤其是params和queryParams .

    在调用 <app-main-component></app-main-component> 之前尝试添加 <router-outlet><router-outlet>

    在此之前,请确保在app-routing>中准备好您的查询参数,从而导出App组件使用的类Route:

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

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

  • 4

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

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

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

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

    param1 = hello
    param2 = 123
    
  • 27

    小心你的路线 . “redirectTo”将删除任何查询参数 .

    const appRoutes: Routes [
     {path: "one", component: PageOneComponent},
     {path: "two", component: PageTwoComponent},
     {path: "", redirectTo: "/one", pathMatch: full},
     {path: "**", redirectTo: "/two"}
    ]
    

    我使用查询参数调用我的主要组件,如“/ main?param1 = a&param2 = b”,并假设我的查询参数在重定向转发生效之前到达主组件中的“ngOnInit()”方法 .

    但这是错误的 . 重定向将在之前出现,删除查询参数并在没有查询参数的情况下调用主组件中的ngOnInit()方法 .

    我改变了我的路线的第三行

    {path: "", component: PageOneComponent},
    

    现在我的查询参数可以在主要组件ngOnInit和PageOneComponent中访问 .

  • 5

    发现于:Parent components gets empty Params from 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();
      }
    
    }
    
  • 1

    您还可以使用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;
      }
    
  • 1

    如果你没有使用Angular路由器试试,querystring . 安装它

    npm install --save querystring
    

    到你的项目 . 在您的组件中执行类似的操作

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

    substring(1) 是必要的,因为如果你有这样的东西 '/mypage?foo=bar' 那么密钥名称将是 ?foo

相关问题