有没有办法在父组件和子组件之间传递数据(这样我就不必多次使用同一个服务)?文件如下所示。
所以我在我的adventure.component.ts
中进行冒险,并希望在我的adventure-detail.component
中保留数据。我知道我可以使用我的服务再次冒险,但有没有办法通过路由器插座传递冒险?
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);
});
}
}
冒险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 })
}
}
答案 0 :(得分:0)
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--);
}
}