在我的 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
}
}
通常我 会 通过
this._router.navigate(['SecondComponent']);
最终通过
this._router.navigate(['SecondComponent', {p1: this.property1, p2: property2 }]);
而带参数的链接的定义是
@RouteConfig([
// ...
{ path: '/SecondComponent/:p1:p2', name: 'SecondComponent', component: SecondComponent}
)]
这种方法的问题是我想 我不能在 url 中传递复杂的数据(例如像 property3 这样的 对象);
第二种方法
另一种方法是将 SecondComponent 作为 指令 包含在 FirstComponent 中。
<SecondComponent [p3]="property3"></SecondComponent>
但是我想 路由 到该组件,而不是包含它!
第三种方法
我在这里看到的最可行的解决方案是使用 服务(例如 FirstComponentService)
- 在 FirstComponent 中的 routeWithData() 上 存储 数据 (_firstComponentService.storeData())
- 在 SecondComponent 的 ngOnInit() 中 检索 数据 (_firstComponentService.retrieveData())
虽然这种方法似乎完全可行,但我想知道这是否是实现目标的最简单/最优雅的方法。
一般来说,我想知道我是否错过了在组件之间传递数据的其他 潜在方法,尤其是 在代码量较少的情况下
原文由 dragonmnl 发布,翻译遵循 CC BY-SA 4.0 许可协议
更新 4.0.0
有关更多详细信息,请参阅 Angular Angular Router - 在导航之前获取数据。
原来的
使用服务是要走的路。在路由参数中,您应该只传递您希望反映在浏览器 URL 栏中的数据。
请参阅 Angular Angular Cookbook 组件通信 - 双向服务。
RC.4附带的路由器重新引入
data
另请参阅 Plunker 。