Sending whole object from one component to another

2019-02-21 04:34发布

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:

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

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

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

My app.routes.ts file contains appropriate routing:

{ path: 'reserve', component: ReserveFormComponent }

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

2条回答
霸刀☆藐视天下
2楼-- · 2019-02-21 05:13

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

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

2)In cinema.component.ts pass the repertoire as param

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

3)Extract the param in reserve-form.component.ts

First of all you need to import

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

Technique 1

repertoire:any;

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

Technique 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.

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.

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.

查看更多
我只想做你的唯一
3楼-- · 2019-02-21 05:25

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)

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)
  }

}
查看更多
登录 后发表回答