Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular passing data through router-outlet

Tags:

angularjs

Is there a way to pass data between parent and child components (so that I don't have to use the same service multiple times)? Files are shown below.

So I'm getting an adventure in my adventure.component.ts, and would like to still data from it in my adventure-detail.component. I know I can get the adventure again using my service, but is there a way to pass the adventure through the router-outlet?

adventure.component.ts:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

import { AdventureService } from './../adventure.service';
import { Adventure } from './../adventure';

@Component({
  moduleId: module.id,
  template: `
    <div *ngIf="adventure">
      <h2>{{adventure.name}}</h2>
    </div>

    <router-outlet></router-outlet>
  `
})

export class AdventureComponent implements OnInit {
  adventure: Adventure;

  constructor(
    private adventureService: AdventureService,
    private route: ActivatedRoute,
    private location: Location
  ) {}

  ngOnInit(): void {
    this.route.params.forEach((params: Params) => {
      let id = +params['id'];
      this.adventureService.getAdventure(id)
        .then(adventure => this.adventure = adventure);
    });
  }
}

adventure-detail.component.ts:

import { Component } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  template:  `
    <span>{{adventure.description}}</span>
  `
})

export class AdventureDetailComponent {

  constructor(
    private route: ActivatedRoute,
    private router: Router
  ) { }

  start(): void {
    this.router.navigate(['./', 'page', 1], { relativeTo: this.route })
  }
}
like image 810
Stephen R Chen Avatar asked Sep 20 '26 12:09

Stephen R Chen


1 Answers

Service:

import {Injectable, EventEmitter} from "@angular/core";    

@Injectable()
export class DataService {
onGetData: EventEmitter = new EventEmitter();

getData() {
  this.http.post(...params).map(res => {
    this.onGetData.emit(res.json());
  })
}

Component:

import {Component} from '@angular/core';    
import {DataService} from "../services/data.service";       

@Component()
export class MyComponent {
  constructor(private DataService:DataService) {
    this.DataService.onGetData.subscribe(res => {
      (from service on .emit() )
    })
  }

  //To send data to all subscribers from current component
  sendData() {
    this.DataService.onGetData.emit(--NEW DATA--);
  }
}
like image 170
egor.xyz Avatar answered Sep 23 '26 02:09

egor.xyz