以角度2将整个对象从一个组件发送到另一个组件 [英] Sending whole object from one component to another in angular 2

查看:103
本文介绍了以角度2将整个对象从一个组件发送到另一个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题。我不知道如何将对象从一个组件发送到另一个组件。

I have a problem. I don't know how to send object from one component to another.

在第一个组件中 cinema.component.html 我有以下函数调用:

In first component cinema.component.html I have following function call:

<a title="Reserve" (click)="openReservationPage(repertoire)">Reserve</a> 

cinema.component.ts 文件中,为。 html 我有类似的东西:

In cinema.component.ts file, for that .html I have something like:

openReservationPage(repertoire: UpcomingRepertoire) {
    this.router.navigate(['/reserve', {repertoire: JSON.stringify(repertoire)}]);
}

我的 app.routes.ts 文件包含适当的路由:

My app.routes.ts file contains appropriate routing:

{ path: 'reserve', component: ReserveFormComponent }

如何在另一个页面 reserve-form.component.ts 保留曲目对象> reserve-form.component.html ?

How can I use this repertoire object in another page reserve-form.component.ts and reserve-form.component.html ?

推荐答案

作为标题中问题的答案,我会表示创建一个服务来在组件之间传递数据。

As an answer for the question in the title, i would said create a service to pass data between components.

由于它是一个路由器实现,你可以将该指令作为路由参数传递。

Since its a router implementation you can pass the repertoire as a route parameter.

请按照以下步骤操作:

1)修改app.routes.ts中的路线以获取参数

{ path: 'reserve/:repertoire', component: ReserveFormComponent }

2)在cinema.component.ts中将曲目作为参数传递

this.router.navigate(['/reserve',JSON.stringify(repertoire)]‌​);

3)在reserve-form.component.ts中提取参数

首先你需要导入

 import {ActivatedRoute } from "@angular/router";

技术1

repertoire:any;

constructor(private activatedRoute: ActivatedRoute) {
    this.repertoire = JSON.parse(activatedRoute.snapshot.params["repertoire"]);
  }

技术2

import { Subscription } from "rxjs/Rx";

private subscription: Subscription;
repertoire:any;

constructor(private activatedRoute: ActivatedRoute) {
    this.subscription = activatedRoute.params.subscribe(
      (param: any) => this.repertoire = JSON.parse(param['repertoire'])
    );
  }

  ngOnDestroy() { // here we unsubscribe to the observable
    this.subscription.unsubscribe();
  }

进一步说明

技术1

技术2 是对已发布param的observable的订阅,但不要忘记在ngOnDestroy()组件的生命周期方法中取消订阅以防止内存泄漏。

Technique 2 is a subscription to the observable once there a param published but don't forget to unsubscribe in the ngOnDestroy() component's life cycle method to prevent memory leak.

这是更优选的,因为有些情况下,在创建快照方法无法捕获的组件之后将参数传递给组件,并且它与基本方案不同的方案更灵活在技​​术1中。

It is more preferable because some times there a scenario that a param is passed to a component after it was created where the snapshot method wouldn't capture and it more flexible with different scenario than the basic one in technique 1.

这篇关于以角度2将整个对象从一个组件发送到另一个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆