我使用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")

当前回答

获取URL参数作为对象。

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

其他回答

如果你只想获得一次查询参数,最好的方法是使用take方法,这样你就不需要担心取消订阅。 下面是一个简单的片段:-

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

注意:如果你想在将来使用参数值,可以删除take(1)。

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

在您使用的组件中访问它

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

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

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

我真的很喜欢@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
}

如果RouterState没有在路由中定义,你就不能从RouterState中获得参数,所以在你的例子中,你必须解析这个querystring…

下面是我使用的代码:

re = /[?&]([^=#&]+)=([^&#]*)/g; 让比赛; let isMatch = true; Let matches = []; while (isMatch) { Match = re.exec(window.location.href); If (match !== null) { match[decodeURIComponent(match[1])] = decodeURIComponent(match[2]); 如果匹配。index === re.lastIndex) { re.lastIndex + +; } } 其他{ isMatch = false; } } console.log(匹配);

我的老办法是:

queryParams(): Map<String, String> {
  var pairs = location.search.replace("?", "").split("&")
  var params = new Map<String, String>()
  pairs.map(x => {
    var pair = x.split("=")
    if (pair.length == 2) {
      params.set(pair[0], pair[1])
    }
  })

  return params
}