您的位置:首页 > Web前端 > AngularJS

angularjs2进阶教程5-路由

2017-03-06 22:13 260 查看
还是 angularjs2入门1-文件结构分析 的源码,将app名称tutorial-step5-router

添加列表视图,两种不同的方式来显示列表。点击列表中的某一项,进入英雄的详情。

详细介绍可以参考angularjs2进阶教程-项目介绍

我们要添加 Angular’s Router。

上节课中已经有了appcomponent将列表和详情显示到一个页面上。

创建一个新的dashboard component列表到路由中。

新建hero-detail.component.ts显示英雄详情。

把appcomponent改为应用程序处理导航定位(2种显示方式:dashboard 和原先的列表,1个导航到详情),和显示英雄列表。

app.component.ts
 file to 
heroes.component.ts

AppComponent
 class to 
HeroesComponent
 (rename
locally, only in this file)
Selector 
my-app
 to 
my-heroes

创建app.component.ts,修改app.module.ts

添加Angular Router

RouterModule.forRoot设置初始导航,RouterOutlet显示路由中的内容

Set the 
moduleId
 property
to 
module.id
 for
module-relative loading of the 
templateUrl
.

在路由中,每个组件都要设置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'],
})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐