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 })
}
}
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());
})
}
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--);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With