Ng2 路由

Angular2中包含了一个路由框架,我们只需要定义一个个的路径和它对应的组件,然后在页面跳转时也是用Angular2的方式就能很方便的实现路由控制。

Angular2的路由包含下面4个部分:

  • 路由定义
  • 路由器
  • 导航
  • 参数

路由定义

路由定义,通俗来讲就是定义一个URL路径,打开的是哪个页面,由哪个组件来控制数据交互和用户交互,页面就是组件定义中定义的这个组件对应的模板页面。

路由器

路由器也就是分发器。当点击一个链接时,就是由他来确定要打开哪一个组件?怎么封装?怎么传递参数。

导航

就是指从一个页面打开另一个页面。有两种方式:

  • 通过页面上的一个链接link
  • 在JS中使用代码导航

参数

当我们在页面之间跳转时,通常都需要传递参数。除了常见的URL参数传递之外,在REST风格的路径设计中,经常使用某一个id作为url的一部分。

最简单的路由配置

S1:设置index.html页面的基址

打开index.html,确保它的区顶部有一个元素(或动态生成该元素的脚本)。

S2:告诉路由器当用户点击链接时,应该显示哪个视图?

  • app.module.ts中导入RouterModule类,并在import数组中添加路径导航如下:

     RouterModule.forRoot([
          {
            path: 'heroes',
            component: HeroesComponent
          }
        ])
  • 路由出口

我们必须告诉路由器它位置,所以我们把标签添加到模板的底部。 RouterOutlet是由RouterModule提供的指令之一。 当我们在应用中导航时,路由器就把激活的组件显示在里面。

  • 路由器链接

导航的标准化配置

S1:在src下新建导航模块

app-routing.module.ts

S2:在文件中导入需要加入路由的组件和路由功能依赖的组件

    
    import { NgModule } from '@angular/core';
    import { HeroDetailComponent } from './hero-detail/hero-detail.component';
    import { DashboardComponent } from './dashboard/dashboard.component';
    import { HeroesComponent } from './heroes/heroes.component';
    
    // 添加路由功能支持
    import { RouterModule, Routes } from '@angular/router';
    // 添加path依赖
    const routes: Routes = [
        {
            path: 'heroes',
            component: HeroesComponent
        },
        {
            path: 'dashboard',
            component: DashboardComponent
        },
        {
            path: '',
            redirectTo: '/dashboard',
            pathMatch: 'full'
        },
        {
            path: 'herodetail/:id',  //带参数或者令牌的路由path
            component: HeroDetailComponent
        }
    ];
    
    @NgModule({
        imports: [RouterModule.forRoot(routes)],
        exports: [RouterModule]
    })
    export class AppRoutingModule { }

S3: 在app.module.ts中添加支持


    // 1. 导入路由模块
    import { AppRoutingModule } from './app-routing.module';
    ...
    //在import数组中添加模块 
    AppRoutingModule      //导入路由模块

S4-1:在html中引入方式


    
    

S4-2:在ts中使用的方法

1. 导入Router路由器组件

import { Router } from '@angular/router';

2. 在constructor中注入路由器实例
    
    constructor(
        private heroServce: HeroService,
        private router: Router) { }
3. 在函数中添加使用,执行函数后会导航到指定的组件页面

     gotoDetail(): void {
        this.router.navigate(['/herodetail', this.selectedHero.id]);
      }

你可能感兴趣的:(Ng2 路由)