为了账号安全,请及时绑定邮箱和手机立即绑定

请问如何将数据传递给Angular路由组件?

请问如何将数据传递给Angular路由组件?

萧十郎 2019-11-17 16:12:57
如何将数据传递给Angular路由组件?在我的一个Angular 2路线的模板(FirstComponent)中,我有一个按钮first.component.html<div class="button" click="routeWithData()">Pass data and route</div>我的目标是实现:按钮单击 - >路由到另一个组件,同时保留数据,而不使用其他组件作为指令。这就是我试过的......第一种方法在同一视图中,我存储基于用户交互收集相同的数据。first.component.tsexport 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())虽然这种方法似乎完全可行,但我想知道这是否是实现目标的最简单/最优雅的方式。一般来说,我想知道我是否缺少其他可能的方法来在组件之间传递数据,特别是在代码量较少的情况下
查看完整描述

3 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

我想因为我们在角度2中没有$ rootScope类似于角度1.x. 我们可以使用angular 2共享服务/类,而在ngOnDestroy中将数据传递给服务,并在路由后从ngOnInit函数中的服务获取数据:

这里我使用DataService来共享英雄对象:

import { Hero } from './hero';export class DataService {
  public hero: Hero;}

从第一页组件传递对象:

 ngOnDestroy() {
    this.dataService.hero = this.hero; 
 }

从第二页组件获取对象:

 ngOnInit() {
    this.hero = this.dataService.hero; 
 }

这是一个例子:plunker



查看完整回答
反对 回复 2019-11-18
  • 3 回答
  • 0 关注
  • 303 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信