如何从Angular 2中的url获取查询参数?

Fir*_*eGM 213 typescript angular

我使用angular2.0.0-beta.7.将组件加载到/path?query=value1重定向到的路径上时/path.为什么要删除GET参数?如何保存参数?

我在路由器中有错误.如果我有像这样的主要路线

@RouteConfig([
  {
      path: '/todos/...',
      name: 'TodoMain',
      component: TodoMainComponent
  }
])
Run Code Online (Sandbox Code Playgroud)

和我的孩子一样的路线

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

然后我无法在TodoListComponent中获取参数.我能得到

params("/my/path;param1=value1;param2=value2") 
Run Code Online (Sandbox Code Playgroud)

但我想要经典

query params("/my/path?param1=value1&param2=value2")
Run Code Online (Sandbox Code Playgroud)

Ste*_*aul 390

通过注入一个实例,ActivatedRoute可以订阅各种可观察对象,包括a queryParamsparamsobservable:

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

}
Run Code Online (Sandbox Code Playgroud)

关于取消订阅的说明

@Reto和@ codef0rmer非常正确地指出,根据官方文档,在这种情况下unsubscribe(),组件onDestroy()方法内部是不必要的.这已从我的代码示例中删除.(请参阅教程的"我是否需要取消订阅?"部分)

  • 从官方文档:**我需要取消订阅吗?**`路由器管理它提供的可观察量并本地化订阅.当组件被销毁时,清理订阅,防止内存泄漏,因此我们不需要取消订阅路径params Observable. (17认同)
  • 我进一步建议用一个承诺替换订阅 - 在这种特殊情况下.this.activatedRoute.params.toPromise().then(response => ...).catch(error => ...); (2认同)

小智 95

当像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"];
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是否意味着您不再需要在routeconfig路径中添加“ /:id”?因为当我使用它时我得到“未定义”,所以我在某处仍然会有错误 (2认同)
  • 大。这是我正在寻找的,因为我需要直接从动态服务器URL中读取参数。我不能使用导航。 (2认同)
  • 我不确定为什么 `quearyParams` 是 `{}`,即使在 `ngOnInit()` 上我对 `this.activatedRoute.queryParams.subscribe((params) => console.log(params))` 进行了更改,它开始了工作正常..我不确定这是否是正确的方法 (2认同)

Roo*_*nen 37

即使问题指定版本为beta 7,这个问题也会出现在谷歌搜索角度为2的查询参数等常见短语的最佳搜索结果.出于这个原因,这是最新路由器的答案(目前在alpha.7中).

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

constructor(private router: Router) { }
Run Code Online (Sandbox Code Playgroud)

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

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

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

仍有一些事情需要注意:

  1. 访问paramslike的属性params['id']总是返回一个字符串,这可以通过前缀来转换为数字+.
  2. 使用observable获取查询参数的原因是它允许重新使用相同的组件实例而不是加载新的组件实例.每次更改查询参数时,它都会导致我们订阅的新事件,因此我们可以相应地对更改做出反应.


cod*_*mer 27

我真的很喜欢@ 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
}
Run Code Online (Sandbox Code Playgroud)

  • 当然,这个问题的警告是,它将是初始值,后续更改将不会被反映出来.因此,如果您以编程方式更改URL参数作为逻辑的一部分,那么您需要注意这些参数 (6认同)

ddd*_*nis 20

发送查询参数

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

接收查询参数

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

官方消息来源


Asa*_*nel 12

您好,您可以使用URLSearchParams,您可以在这里阅读更多相关信息.

进口:

import {URLSearchParams} from "@angular/http";
Run Code Online (Sandbox Code Playgroud)

和功能:

getParam(){
  let params = new URLSearchParams(window.location.search);
  let someParam = params.get('someParam');
  return someParam;
}
Run Code Online (Sandbox Code Playgroud)

注意:所有平台都不支持它,并且有角度的文档似乎处于"实验"状态

  • 这对我不起作用.我发现window.location.search包含查询字符串参数的前导问号.因此,第一个参数的键将具有前置问号. (2认同)

Nam*_*rna 7

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

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

    constructor(params: RouteParams){
    var val = params.get("query");
    }
Run Code Online (Sandbox Code Playgroud)

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

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

  • 这个解决方案已弃用! (4认同)

小智 7

您可以使用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']));
  }

}
Run Code Online (Sandbox Code Playgroud)


Jso*_*ras 7

获取URL参数作为对象.

import { Router } from '@angular/router';
constructor(private router: Router) {
    console.log(router.parseUrl(router.url));
}
Run Code Online (Sandbox Code Playgroud)