首页 文章

如何从角度2中的URL获取查询参数?

提问于
浏览
165

我使用angular2.0.0-beta.7 . 当组件加载到路径上时,如“/ path?query = value1”,它将被重定向到“/ path” . 为什么删除了GET参数?我怎样才能保留params?

我在路由器中有错误 . 如果我有一条主要路线

@RouteConfig([
  {
      path: '/todos/...',
      name: 'TodoMain',
      component: TodoMainComponent
  }
])

和我的孩子一样的路线

@RouteConfig([
  { path: '/', component: TodoListComponent, name: 'TodoList', useAsDefault:true },
  { path: '/:id', component: TodoDetailComponent, name:'TodoDetail' }
])

我无法在TodoListComponent中获取params .

我可以得到矩阵

params("/my/path;param1=value1;param2=value2")

但我想要经典

query params("/my/path?param1=value1&param2=value2")

15 回答

  • 14

    通过注入 ActivatedRoute 的实例,可以订阅各种可观察对象,包括 queryParamsparams observable:

    import {Router, ActivatedRoute, Params} from '@angular/router';
    import {OnInit, Component} from '@angular/core';
    
    @Component({...})
    export class MyComponent implements OnInit {
    
      constructor(private activatedRoute: ActivatedRoute) {}
    
      ngOnInit() {
        // Note: Below 'queryParams' can be replaced with 'params' depending on your requirements
        this.activatedRoute.queryParams.subscribe(params => {
            const userId = params['userId'];
            console.log(userId);
          });
      }
    
    }
    

    A NOTE REGARDING UNSUBSCRIBING

    @Reto和@ codef0rmer非常正确地指出,根据官方文档,在这个实例中,组件 onDestroy() 方法中的 unsubscribe() 是不必要的 . 这已从我的代码示例中删除 . (参见this教程的 Do I need to unsubscribe? 部分)

  • 321

    当这样的网址http://stackoverflow.com?param1=value

    您可以通过以下代码获取param1:

    import { Component, OnInit } from '@angular/core';
    import { Router, ActivatedRoute, Params } from '@angular/router';
    
    @Component({
        selector: '',
        templateUrl: './abc.html',
        styleUrls: ['./abc.less']
    })
    export class AbcComponent implements OnInit {
        constructor(private route: ActivatedRoute) { }
    
        ngOnInit() {
            // get param
            let param1 = this.route.snapshot.queryParams["param1"];
        }
    }
    
  • 31

    尽管问题指定版本为beta 7,但此问题也会出现在Google上针对常见短语(如angular 2查询参数)的最高搜索结果 . 出于这个原因,这是最新路由器的答案(目前在alpha.7中) .

    读取参数的方式发生了巨大变化 . 首先,您需要在构造函数参数中注入名为 Router 的依赖项,例如:

    constructor(private router: Router) { }
    

    之后我们可以在 ngOnInit 方法上订阅查询参数(构造函数也可以,但 ngOnInit 应该用于可测试性)

    this.router
      .routerState
      .queryParams
      .subscribe(params => {
        this.selectedId = +params['id'];
      });
    

    在这个例子中,我们从URL读取查询参数id,如 example.com?id=41 .

    仍有一些事情需要注意:

    • params['id'] 一样访问 params 的属性总是返回一个字符串,这可以通过在前面添加 + 来转换为数字 .

    • 使用observable获取查询参数的原因是它允许重新使用相同的组件实例而不是加载新的组件实例 . 每次更改查询参数时,都会导致我们订阅的新事件,因此我们可以相应地对更改做出反应 .

  • 5

    我真的很喜欢@ StevePaul的答案,但我们可以做同样的事情而无需额外的订阅/取消订阅 .

    import { ActivatedRoute } from '@angular/router';
    constructor(private activatedRoute: ActivatedRoute) {
        let params: any = this.activatedRoute.snapshot.params;
        console.log(params.id);
        // or shortcut Type Casting
        // (<any> this.activatedRoute.snapshot.params).id
    }
    
  • 7

    发送查询参数

    import { Router } from '@angular/router';
    this.router.navigate([ '/your-route' ], { queryParams: { key: va1, keyN: valN } });
    

    接收查询参数

    import { ActivatedRoute } from '@angular/router';
    this.activatedRoute.queryParams.subscribe(params => {
        let value_1 = params['key'];
        let value_N = params['keyN'];
    });
    

    Official source

  • 0

    您好,您可以使用URLSearchParams,您可以阅读更多关于它here .

    进口:

    import {URLSearchParams} from "@angular/http";
    

    和功能:

    getParam(){
      let params = new URLSearchParams(window.location.search);
      let someParam = params.get('someParam');
      return someParam;
    }
    

    Notice :所有平台都不支持它,并且似乎是由角度文档处于"EXPERIMENTAL"状态

  • 77

    首先,我发现使用Angular2的是带有查询字符串的url是/ path; query = value1

    要在您使用的组件中访问它,请执行此操作,但现在遵循代码块:

    constructor(params: RouteParams){
        var val = params.get("query");
        }
    

    至于为何在加载组件时将其删除,这不是默认行为 . 我在一个干净的测试项目中进行了具体检查,没有重定向或更改 . 它是默认路由还是其他与路由有关的特殊路由?

    https://angular.io/docs/ts/latest/guide/router.html#!#query-parameters的Angular2教程中阅读有关查询字符串和参数的路由

  • 11

    您可以使用ActivatedRoute在URL中传递查询参数,如下所述: -

    网址: - http:/domain.com?test = abc

    import { Component } from '@angular/core';
    import { ActivatedRoute }     from '@angular/router';
    
    @Component({
      selector: 'my-home'
    })
    export class HomeComponent {
    
      constructor(private sharedServices : SharedService,private route: ActivatedRoute) { 
        route.queryParams.subscribe(
          data => console.log('queryParams', data['test']));
      }
    
    }
    
  • 24

    获取URL参数作为对象 .

    import { Router } from '@angular/router';
    constructor(private router: Router) {
        console.log(router.parseUrl(router.url));
    }
    
  • 0

    如果您只想获取一次查询参数,最好的方法是使用 take 方法,这样您就不必担心取消订阅了 . 这是简单的片段: -

    constructor(private route: ActivatedRoute) {
      route.snapshot.queryParamMap.take(1).subscribe(params => {
         let category = params.get('category')
         console.log(category);
      })
    }
    

    Note: 如果要在将来使用参数值,请删除 take(1) .

  • 2

    现在它是:

    this.activatedRoute.queryParams.subscribe((params: Params) => {
      console.log(params);
    });
    
  • 7

    我希望它会帮助别人 .

    上面的问题表明,在页面被重定向后需要查询参数值,我们可以假设快照值(无可观察的替代)就足够了 .

    这里没有人提到official documentation中的snapshot.paramMap.get .

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

    所以在发送之前,在发送/重定向组件中添加它:

    import { Router } from '@angular/router';
    

    然后重新指向(记录here):

    this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);
    

    或者干脆:

    this.router.navigate(['/heroes', heroId ]);
    

    确保已在路由模块中添加了此文档here

    { path: 'hero/:id', component: HeroDetailComponent }
    

    最后,在您需要使用查询参数的组件中

    • 添加导入(记录here):
    import { Router, ActivatedRoute, ParamMap } from '@angular/router';
    
    • 注入ActivatedRoute

    (文档还导入switchMap并注入了Router和HeroService - 但它们仅用于可观察的替代方案 - 在我们使用快照替代时不需要它们):

    constructor(
          private route: ActivatedRoute
        ) {}
    
    • 并获得您需要的值(记录here):
    ngOnInit() {
      const id = this.route.snapshot.paramMap.get('id');
    }
    

    注意:如果您将路由模块添加到功能模块(如文档中所示),请确认APP.MODULE.ts中的路由模块在AppRoutingModule(或具有根级应用程序路由的其他文件)之前进入IN IMPORTS:[] . 其他特征路线将无法找到(因为它们将在{路径:'**',redirectTo:'/ not-found'}之后出现,您将看到只有未找到的消息) .

  • 0

    你不能得到一个如果未在路由中定义,则来自RouterState的参数,因此在您的示例中,您必须解析查询字符串...

    这是我使用的代码:

    let re = /[?&]([^=#&]+)=([^&#]*)/g;
    let match;
    let isMatch = true;
    let matches = [];
    while (isMatch) {
        match = re.exec(window.location.href);
        if (match !== null) {
            matches[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
            if (match.index === re.lastIndex) {
                re.lastIndex++;
            }
        }
        else {
            isMatch = false;
        }
    }
    console.log(matches);
    
  • 1

    史蒂夫保罗的解决方案的变体,我更喜欢避免不必要的ivars,所以为了在 ngOnDestroy 期间删除对 unsubscribe() 调用的需要,只需用 take(1) 订阅observable,它将在第一个值之后自动释放 - 防止内存泄漏

    import 'rxjs/add/operator/take';
    import {Router, ActivatedRoute} from '@angular/router';
    
    @Component({...})
    export class MyComponent implements OnInit {
    
      constructor(private activatedRoute: ActivatedRoute) {
        this.activatedRoute.params.take(1).subscribe((params: any) => {
          let userId = params['userId'];
          console.log(userId);
        });
      }
    
    }
    
  • 2

    You just need to inject ActivatedRoute in constructor and then just access params or queryParams over it

    constructor(private route:AcitvatedRoute){}
    ngOnInit(){
            this.route.queryParams.subscribe(params=>{
            let username=params['username'];
          });
     }
    

    在某些情况下,它没有在NgOnInit中给出任何东西...可能是因为在启动params之前的init调用,在这种情况下你可以通过要求observable等待一段时间来实现这个功能debounceTime(1000)

    e.g =>

    constructor(private route:AcitvatedRoute){}
        ngOnInit(){
                this.route.queryParams.debounceTime(100).subscribe(params=>{
                let username=params['username'];
              });
         }
    

    debounceTime() Emits a value from source observable only after perticular time span passed without another source emission

相关问题