还是angularjs2入门1-文件结构分析的源码,将app名称tutorial-step5-router
添加列表视图,两种不同的方式来显示列表。点击列表中的某一项,进入英雄的详情。
详细介绍可以参考angularjs2进阶教程-项目介绍
我们要添加Angular’s Router。
上节课中已经有了appcomponent将列表和详情显示到一个页面上。
创建一个新的dashboard component列表到路由中。
新建hero-detail.component.ts显示英雄详情。
把appcomponent改为应用程序处理导航定位(2种显示方式:dashboard 和原先的列表,1个导航到详情),和显示英雄列表。
-
app.component.tsfile toheroes.component.ts AppComponentclass toHeroesComponent(rename locally,onlyin this file)- Selector
my-apptomy-heroes
创建app.component.ts,修改app.module.ts
添加Angular Router
Set themoduleIdproperty tomodule.idfor module-relative loading of thetemplateUrl.
在路由中,每个组件都要设置moduleId: module.id,这样为了在导航到某个路由时,加载相应的页面
1.创建dashboard.component.ts
@Component({
moduleId: module.id,selector: 'my-dashboard',templateUrl: './dashboard.component.html',styleUrls: [ './dashboard.component.css' ]
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(private heroService: HeroService) { }
ngOnInit(): void {
this.heroService.getHeroes()
.then(heroes => this.heroes = heroes.slice(1,5));
}
}
2.新建hero-detail.component.ts
@Component({
moduleId: module.id,selector: 'my-hero-detail',templateUrl: './hero-detail.component.html',styleUrls: [ './hero-detail.component.css' ]
})
export class HeroDetailComponent implements OnInit {
hero: Hero;
constructor(
private heroService: HeroService,private route: ActivatedRoute,private location: Location
) {}
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.heroService.getHero(+params['id']))
.subscribe(hero => this.hero = hero);
}
goBack(): void {
this.location.back();
}
}3.建立路由组件app-routing.module.ts
const routes: Routes = [
{ path: '',redirectTo: '/dashboard',pathMatch: 'full' },{ path: 'dashboard',component: DashboardComponent },{ path: 'detail/:id',component: HeroDetailComponent },{ path: 'heroes',component: HeroesComponent }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],exports: [ RouterModule ]
})4.app.component.ts
@Component({
moduleId: module.id,selector: 'my-app',template: `
<h1>{{title}}</h1>
<nav>
<a routerLink="/dashboard" routerLinkActive="active">Dashboard</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>
`,styleUrls: ['./app.component.css'],})