1
有沒有辦法在父組件和子組件之間傳遞數據(這樣我就不必多次使用相同的服務)?文件如下所示。通過路由器插座角度傳遞數據
因此,我在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 })
}
}