在Angular路由器中动态传递数据 [英] Pass data in Angular router dynamically
问题描述
我试图将数据(对象)从一个组件发送到另一个组件,但是我得到的结果为空.
I am trying to send data(Object) from one component to another however I am getting an empty result.
这是我的代码
路由模块
routing module
{ path: 'booking/details', component: DetailsComponent, data: { title: extract('Details'), dataTransfer: '' } },
发送组件
sending component
this.router.navigate(['/booking/details', this.caseData]);
this.caseData看起来像这样
this.caseData looks like this
{
"getAllInfo": {
"ticket": {
"internalNum": "12345",
"comp": "11"
},
"caseInfo": {
"masVolgnommer": "1",
"masMaand": "1",
"masJaar": "2010"
}
}
}
接收组件
receiving component
this.caseData = this.route
.data
.subscribe(v => console.log(v.dataTransfer));
推荐答案
您的路由中不需要数据属性-如果不添加数据,则可以将数据作为json绑定并读取{ path: 'booking/details', component: DetailsComponent }
,这样可以在路由时传递数据-而路线声明中的data属性用于每次导航路线时
Data property is not needed in your route - without adding data you can bind data as a json and read it { path: 'booking/details', component: DetailsComponent }
this is fine to pass data while routing - whereas data property in your route declaration is used to pass data every time when the route is navigated
每次尝试导航booking/details
时,您都会获得数据{title: "Details", dataTransfer: ""}
来读取此数据,您可以将ActivatedRouteSnapshot
注入到构造函数中并读取为
When you try to navigate booking/details
everytime you will get data {title: "Details", dataTransfer: ""}
to read this data you can inject ActivatedRouteSnapshot
in your constructor and read as
this.activatedRouteSnapshot.data["title"]
这将返回详细信息
在您的情况下,如果要将数据传递到另一个组件,只需将数据作为Json传递
In your case if you want to pass data to another component just pass the data as a Json
this.router.navigate(['/booking/details', { caseData : this.caseData }]);
最后,您可以按照上述相同的方式读取数据-this.activatedRouteSnapshot.data["caseData"]
Finally you can read the data in the same way mentioned above - this.activatedRouteSnapshot.data["caseData"]
希望这行得通-祝您编程愉快!
Hope this works - Happy coding !!
这篇关于在Angular路由器中动态传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!