问题描述
我使用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¶m2=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获取查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!