Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了angularjs2进阶教程5-路由大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

还是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@H_789_31@my-appto@H_789_31@my-heroes
创建app.component.ts,修改app.module.ts
添加Angular Router

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

Set the@H_226_79@modulEIDproperty to@H_789_31@module.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'],})

大佬总结

以上是大佬教程为你收集整理的angularjs2进阶教程5-路由全部内容,希望文章能够帮你解决angularjs2进阶教程5-路由所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。