最佳答案
在Angular 2的一个路由模板(FirstComponent)中,我有一个按钮
first.component.html
<div class="button" click="routeWithData()">Pass data and route</div>
我的目标是为了实现:
按钮点击->路由到另一个组件,同时保留数据,而不使用另一个组件作为指令。
这是我试过的…
1号的方法
在同一个视图中,我根据用户交互存储收集相同的数据。
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;
2方法
另一种方法是将SecondComponent作为指令包含在FirstComponent中。
<SecondComponent [p3]="property3"></SecondComponent>
然而,我想路线到该组件,不包括它!
第三个方法
我在这里看到的最可行的解决方案是使用服务(例如FirstComponentService)来
虽然这种方法似乎完全可行,但我想知道这是否是实现目标的最简单/最优雅的方法。
一般来说,我想知道我是否缺少其他潜在的方法来在组件之间传递数据,特别是用尽可能少的代码