参考来源:https://www.angular.cn/tutorial/toh-pt5#add-dashboard-link-to-the-shell
1、配置路由模块app\app-routing.module.ts
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {HeroesComponent} from './heroes/heroes.component';
import {DashboardComponent} from './dashboard/dashboard.component';
import {HeroDetailComponent} from './hero-detail/hero-detail.component';
const routes: Routes = [
{path: '', redirectTo: '/dashboard', pathMatch: 'full'},
{path: 'heroes', component: HeroesComponent},
{path: 'dashboard', component: DashboardComponent},
{path: 'detail/:id', component: HeroDetailComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
2、使用路由app\app.component.html
{{title}}
3、英雄服务app\service\hero.service.ts
import {Injectable} from '@angular/core';
import {Hero} from '../hero';
import {HEROES} from '../mock-heroes';
import {Observable, of} from 'rxjs';
import {MessageService} from './message.service';
@Injectable()
export class HeroService {
constructor(private messageService: MessageService) {
}
getHeroes(): Observable {
this.messageService.add('HeroService: fetched heroes');
return of(HEROES);
}
getHero(id: number): Observable {
this.messageService.add(`HeroService: frtched hero id ${id}`);
return of(HEROES.find(hero => hero.id === id));
}
}
4、英雄列表模板app\heroes\heroes.component.html
My Heroes
5、英雄仪表盘模板app\dashboard\dashboard.component.html
Top Heroes
6、英雄详情模板app\hero-detail\hero-detail.component.html
*ngIf="hero">
{{ hero.name | uppercase }} Detail
id:{{hero.id}}
name:
[(ngModel)]="hero.name" placeholder="name">
go back
7、英雄详情组件app\hero-detail\hero-detail.component.ts
import {Component, OnInit} from '@angular/core';
import {Hero} from '../hero';
import {ActivatedRoute} from '@angular/router';
import {HeroService} from '../service/hero.service';
import {Location} from '@angular/common';
@Component({
selector: 'app-hero-detail',
templateUrl: './hero-detail.component.html',
})
export class HeroDetailComponent implements OnInit {
hero: Hero;
constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) {
}
ngOnInit(): void {
this.getHero();
}
getHero(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id).subscribe(data => {
this.hero = data;
});
}
goBack(): void {
this.location.back();
}
}