订阅Angular 2中的路由参数和数据 [英] Subscribing to route params and data in Angular 2
问题描述
我的表单需要访问路由参数和数据.它们是可观察的,因此我需要订阅才能访问它们的值.我的问题是,如何在单个订阅中同时访问它们?
My form needs to access route params and data. They're observables so i need to subscribe to access their values. My question is, how do i access them both together in a single subscribe?
this._route.params.subscribe(
params => {
getData(params['id'], data['id2'] <=== i need data value too. how do i get this???)
});
为什么角度将它们放在两个单独的可观察对象中?
Why does angular put them in 2 separate observables?
推荐答案
我如何在单个订阅中同时访问它们?
how do i access them both together in a single subscribe?
您可以使用 ActivatedRouteSnapshot
从您的ActivatedRoute
中. ActivatedRouteSnapshot
界面具有params
和queryParams
属性,您可以同时获取这两个值.
You could use ActivatedRouteSnapshot
from your ActivatedRoute
. ActivatedRouteSnapshot
interface has params
and queryParams
property, and you could get the both value at the same time.
请勿尝试直接注入ActivatedRouteSnapshot
.它不会工作.您必须注入ActivatedRoute
并访问其snapshot
属性.
Don't try to inject ActivatedRouteSnapshot
directly. It won't work. You must inject ActivatedRoute
and access its snapshot
property.
注意:这项技术只能获取参数的初始值
Note: We only get the initial value of the parameters with this technique
constructor(private _route: ActivatedRoute) {
console.log(this._route.snapshot.params);
console.log(this._route.snapshot.data);
}
示例柱塞
另一种方法,因为params
和data
是observable
,我们可以使用
Another way, since params
and data
are observable
, we could use zip
operator to merge them, then access them in a single subscribe. But be aware that if one of params
or data
do not have value, then the subscribe will not be triggered.
this._route.params
.zip(this._route.data)
.subscribe((value) => {
this.id = value[0]["id"]; // get param
this.data = value[1]; // get data value
});
示例柱塞
为什么角度将它们放在两个单独的可观察对象中?
Why does angular put them in 2 separate observables?
我已经阅读了文档,您是对的,它们存在于单独的可观察对象中,但是我不知道为什么.
I have read the documentation, and you are correct,there are in separate observables, but I do not know why.
这篇关于订阅Angular 2中的路由参数和数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!