【发布时间】:2016-08-18 12:32:15
【问题描述】:
在我的 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}
)]
这种方法的问题是我猜 我无法在 URL 中传递复杂的数据(例如,像 property3 这样的 object);
第二种方法
另一种方法是将 SecondComponent 作为 directive 包含在 FirstComponent 中。
<SecondComponent [p3]="property3"></SecondComponent>
但是我想路由到那个组件,而不是包含它!
第三种方法
我在这里看到的最可行的解决方案是使用 Service(例如 FirstComponentService)来
- 将数据 (_firstComponentService.storeData()) 存储在 FirstComponent 中的 routeWithData() 上
- 在 SecondComponent 的 ngOnInit() 中检索数据 (_firstComponentService.retrieveData())
虽然这种方法似乎完全可行,但我想知道这是否是实现目标的最简单/最优雅的方法。
总的来说,我想知道我是否遗漏了其他可能的方法在组件之间传递数据,尤其是代码量较少
【问题讨论】:
-
感谢@Prashobh。
Pass data using Query Parameters是我想要的。你的 link 拯救了我的一天。 -
@Prashobh 非常感谢。您分享的链接非常有用
标签: angular typescript