我使用angular2.0.0-beta.7。当组件加载在/path?Query =value1它被重定向到/path。为什么GET参数被移除?如何保存参数?

我的路由器出错了。如果我有一条主干道

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

我的孩子就像

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

那么我就不能在TodoListComponent中获得参数。我所能得到的

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

但我想要经典的

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

当前回答

通过注入ActivatedRoute实例,可以订阅各种可观察对象,包括queryParams和params可观察对象:

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

}

关于取消订阅的说明

@Reto和@codef0rmer已经非常正确地指出,根据官方文档,组件onDestroy()方法中的unsubscribe()在这种情况下是不必要的。这已从我的代码示例中删除。(请参见本教程中的蓝色警告框)

其他回答

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

在您使用的组件中访问它

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

至于为什么它会在加载组件时被删除,这不是默认行为。我在一个干净的测试项目中特别检查,没有被重定向或更改。它是默认路由还是其他关于路由的特殊的东西?

在https://angular.io/docs/ts/latest/guide/router.html#上阅读关于使用查询字符串和参数进行路由的Angular2教程!#查询参数

尽管这个问题指定的是测试版7,但在谷歌上,这个问题也会出现在常见短语(如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属性总是返回一个字符串,可以通过添加+前缀将其转换为数字。 使用可观察对象获取查询参数的原因是,它允许重用相同的组件实例,而不是加载一个新的组件实例。每次查询参数被更改时,它都会引起一个我们已经订阅的新事件,因此我们可以对更改做出相应的反应。

通过注入ActivatedRoute实例,可以订阅各种可观察对象,包括queryParams和params可观察对象:

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

}

关于取消订阅的说明

@Reto和@codef0rmer已经非常正确地指出,根据官方文档,组件onDestroy()方法中的unsubscribe()在这种情况下是不必要的。这已从我的代码示例中删除。(请参见本教程中的蓝色警告框)

当URL是这样的时候 http://stackoverflow.com?param1=value

你可以通过下面的代码得到参数1:

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"];
    }
}

你只需要在构造函数中注入ActivatedRoute,然后在它上面访问params或queryParams

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

在某些情况下,它在NgOnInit中不给出任何东西…可能是因为在初始化参数之前调用了init,在这种情况下,你可以通过函数debounceTime(1000)让可观察对象等待一段时间来实现这一点

如= >

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

debounceTime()仅在特定的时间跨度过去而没有另一个源发射后,才从源可观察对象发出一个值