加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs2进阶教程5-路由

发布时间:2020-12-17 09:34:12 所属栏目:安全 来源:网络整理
导读:还是 angularjs2入门1-文件结构分析 的源码,将app名称tutorial-step5-router 添加列表视图,两种不同的方式来显示列表。点击列表中的某一项,进入英雄的详情。 详细介绍可以参考angularjs2进阶教程-项目介绍 我们要添加Angular’s Router。 上节课中已经有

还是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)
  • Selectormy-apptomy-heroes
创建app.component.ts,修改app.module.ts
添加Angular Router

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

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'],})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读