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

当前回答

如果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(匹配);

其他回答

查询和路径(Angular 8)

如果你有像https://myapp.com/owner/123/show?height=23这样的url,那么使用

combineLatest( [this.route.paramMap, this.route.queryParamMap] )
  .subscribe( ([pathParams, queryParams]) => {
    let ownerId = pathParams.get('ownerId');    // =123
    let height  = queryParams.get('height');    // =height
    // ...
  })

更新

如果你使用this.router.navigate([yourUrl]);你的查询参数被嵌入到你的URL字符串中,然后angular对URL进行编码,你会得到类似https://myapp.com/owner/123/show%3Fheight%323的东西——以上解决方案会给出错误的结果(queryParams将为空,如果它在路径端,查询参数可以粘在last path param上)。在这种情况下,改变导航的方式

this.router.navigateByUrl(yourUrl);

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

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

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

获取URL参数作为对象。

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

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

现在是:

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