如何将数据传递给Angular路由组件?
在我的一个Angular 2路线的模板(FirstComponent)中,我有一个按钮
first.component.html
<div class="button" click="routeWithData()">Pass data and route</div>
我的目标是实现:
按钮单击 - >路由到另一个组件,同时保留数据,而不使用其他组件作为指令。
这就是我试过的......
第一种方法
在同一视图中,我存储基于用户交互收集相同的数据。
first.component.ts
export class FirstComponent {
constructor(private _router: Router) { }
property1: number;
property2: string;
property3: TypeXY; // this a class, not a primitive type
// here some class methods set the properties above
// DOM events
routeWithData(){
// here route
}}一般情况下我路由SecondComponent通过
this._router.navigate(['SecondComponent']);
最终传递数据
this._router.navigate(['SecondComponent', {p1: this.property1, p2: property2 }]);而带参数的链接的定义是
@RouteConfig([
// ...
{ path: '/SecondComponent/:p1:p2', name: 'SecondComponent', component: SecondComponent} )]这种方法的问题是我猜我无法传递复杂数据(例如像property3这样的对象)in-url;
第二种方法
另一种方法是在FirstComponent中包含SecondComponent作为指令。
<SecondComponent [p3]="property3"></SecondComponent>
但是我想要路由到该组件,而不是包含它!
第三种方法
我在这里看到的最可行的解决方案是使用服务(例如FirstComponentService)
将数据(_firstComponentService.storeData())存储在FirstComponent中的routeWithData()上
在SecondComponent中的ngOnInit()中检索数据(_firstComponentService.retrieveData())
虽然这种方法似乎完全可行,但我想知道这是否是实现目标的最简单/最优雅的方式。
一般来说,我想知道我是否缺少其他可能的方法来在组件之间传递数据,特别是在代码量较少的情况下
萧十郎
HUWWW
随时随地看视频慕课网APP
相关分类