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

新手上路,请多包涵

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

原文由 FireGM 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 785
2 个回答

通过注入 ActivatedRoute 的实例,可以订阅各种 observables,包括 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);
      });
  }

}

关于退订的说明

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

原文由 Stephen Paul 发布,翻译遵循 CC BY-SA 4.0 许可协议

我的老派解决方案:

 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
}

原文由 Alexandr 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进