简体   繁体   English

将整个对象从一个组件发送到另一个组件,角度为2

[英]Sending whole object from one component to another in angular 2

I have a problem. 我有个问题。 I don't know how to send object from one component to another. 我不知道如何将对象从一个组件发送到另一个组件。

In first component cinema.component.html I have following function call: 在第一个组件Cinema.component.html中,我具有以下函数调用:

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

In cinema.component.ts file, for that .html I have something like: Cinema.component.ts文件中,对于该.html,我有类似以下内容:

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

My app.routes.ts file contains appropriate routing: 我的app.routes.ts文件包含适当的路由:

{ path: 'reserve', component: ReserveFormComponent }

How can I use this repertoire object in another page reserve-form.component.ts and reserve-form.component.html ? 如何在另一个页面reserve-form.component.tsreserve-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. 由于是路由器实现,因此您可以将曲目作为路由参数传递。

Follow these steps: 跟着这些步骤:

1)Modify the route in app.routes.ts to take a param 1)在app.routes.ts中修改路线以获取参数

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

2)In cinema.component.ts pass the repertoire as param 2)在cinema.component.ts中将曲目作为参数传递

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

3)Extract the param in reserve-form.component.ts 3)在reserve-form.component.ts中提取参数

First of all you need to import 首先,您需要导入

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

Technique 1 技术1

repertoire:any;

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

Technique 2 技术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();
  }

Further Explanation : 进一步说明

Technique 1 is adopted when you are sure that the param will be passed every time you navigate to the component. 当您确定每次导航到组件时都会传递参数时,将采用技术1

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. 一旦发布了一个参数, 技术2就是对可观察对象的订阅,但是不要忘记取消订阅ngOnDestroy()组件的生命周期方法以防止内存泄漏。

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. 最好使用这种方法,因为有时在创建参数后将参数传递给组件的情况下,快照方法将无法捕获,并且在不同的情况下它比技术1中的基本方法更灵活。

The link below explains how you can do this. 下面的链接说明了如何执行此操作。 I've recently used this to create a messaging service. 我最近使用它来创建消息传递服务。 The example below, shows the code for a simple messaging service. 下面的示例显示了简单消息传递服务的代码。 It allows you to pass a number between components, just change the to I guess. 它允许您在组件之间传递一个数字,只需将其更改为。 You can also write out to local storage, but It seems services are more popular. 您也可以写出本地存储,但是服务似乎更受欢迎。 Once you've got your head around them, they're easy to re-use. 一旦掌握了它们,它们就很容易重复使用。

Hope this helps 希望这可以帮助

Sharing Data Between Angular Components - Four Methods 在角度组件之间共享数据-四种方法

Message Service (PmMessageService) 消息服务(PmMessageService)

import { Injectable } from '@angular/core';
import { BehaviorSubject }    from 'rxjs/BehaviorSubject';

@Injectable()
export class PmMessageService
{

  private pillMenuIndexBS = new BehaviorSubject <number> (null);

  pillMenuIndex = this.pillMenuIndexBS.asObservable();

  constructor() {}

  setPillMenuIndex(index : number)
  {
    this.pillMenuIndexBS.next(index);
  }

}

Component consuming message service, setting a value 消耗组件的消息服务,设置一个值

import { Component, OnInit } from '@angular/core';
import { PmMessageService } from '../pm-message-service/pm-message.service'
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

@Component({
  selector: 'app-pm-configure',
  templateUrl: './pm-configure.component.html',
  styleUrls: ['./pm-configure.component.css']
})

export class PmConfigureComponent implements OnInit
{

  constructor (private messageService : PmMessageService) {}

  ngOnInit()
  {
    this.messageService.setPillMenuIndex(1);
  }

}

Component consuming and subscribing. 组件消耗和订阅。

import { Component, OnInit } from '@angular/core';
import { PmMessageService } from '../pm-message-service/pm-message.service'
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

@Component({
  selector: 'pm-bs-navbar',
  templateUrl: './pm-bs-navbar.component.html',
  styleUrls: ['./pm-bs-navbar.component.css']
})

export class PmBsNavbarComponent implements OnInit
{

  tabActiveNumber;

  constructor (private messageService : PmMessageService) {}

  ngOnInit()
  {
    this.messageService.pillMenuIndex.subscribe(index => this.tabActiveNumber = index)
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM