如何从 Angular 2 中的 url 获取查询参数? [英] How to get query params from url in Angular 2?

查看:22
本文介绍了如何从 Angular 2 中的 url 获取查询参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 angular2.0.0-beta.7.当一个组件加载到像 /path?query=value1 这样的路径上时,它会被重定向到 /path.为什么删除了 GET 参数?如何保留参数?

I use angular2.0.0-beta.7. When a component is loaded on a path like /path?query=value1 it is redirected to /path. Why were the GET params removed? How can I preserve the parameters?

我在路由器中有错误.如果我有像

I have an error in the routers. If I have a main route like

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

和我的孩子路线像

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

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

then I can't get params in TodoListComponent. I am able to get

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

但我想要经典

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

推荐答案

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

By injecting an instance of ActivatedRoute one can subscribe to a variety of observables, including a queryParams and a params 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 非常正确地指出,根据官方文档,组件 onDestroy() 中的 unsubscribe() 方法在此是不必要的实例.这已从我的代码示例中删除.(请参阅教程中的蓝色警告框)

@Reto and @codef0rmer had quite rightly pointed out that, as per the official docs, an unsubscribe() inside the components onDestroy() method is unnecessary in this instance. This has been removed from my code sample. (see blue alert box in this tutorial)

这篇关于如何从 Angular 2 中的 url 获取查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆