天天看点

angular中路由的使用

一、路由的基本使用

  • 1、创建两个组件
    ng g c components/home
    ng g c components/news
               
  • 2、在

    app-routing.module.ts

    中配置路由
    const routes: Routes = [
      // 默认访问地址
      {
        path: '',
        redirectTo: 'home',
        pathMatch: 'full'
      },
      {
        path: 'home',
        component: HomeComponent
      },
      {
        path: 'news',
        component: NewsComponent
      },
      // 当没有匹配的时候就到home路由
      {
        path: '**',
        redirectTo: 'home',
        pathMatch: 'full'
      }
    ];
               
  • 3、使用路由跳转
    <ul>
      <li>
        <a routerLink="home">首页</a>
      </li>
      <li>
        <a routerLink="news">新闻</a>
      </li>
    </ul>
    <!-- 路由切换的槽 -->
    <router-outlet></router-outlet>
               

二、几种路由跳转的方式

  • 1、方式一直接使用
  • 2、动态传递值的方式

三、路由选中的样式

四、动态路由

  • 1、配置路由文件
    ...
    {
      path: 'news',
      component: NewsComponent
    },
    {
      path: 'news/:id',
      component: DetailComponent
    },
    ...
               
  • 2、配置路由的跳转
    <ul>
      <li *ngFor="let item of articleList">
        <a [routerLink]="['/news', item.id]">{{item.title}}</a>
        <!-- 
          <a routerLink="/news/{{item.id}}">跳转到详情</a>
         -->
      </li>
    </ul>
               
  • 3、获取动态路由传递过来的值
    import { ActivatedRoute } from '@angular/router';
    ...
    private sub: any;
      constructor(private readonly route: ActivatedRoute) {}
    
      ngOnInit() {
        console.log(this.route);
        this.sub = this.route.params.subscribe((params: any) => {
          console.log(params);
        });
        // 或者使用snapshot是路由的一个快照【id为你写的动态路由的】
        console.log(this.route.snapshot.paramMap.get('id'));
      }
      ngOnDestroy() {
        this.sub.unsubscribe();
      }
    }
               

五、使用

query

传递参数

  • 1、路由跳转的时候
    <a
      [routerLink]="['news']"
      [queryParams]="{ id: 1, name: 'hello', age: 20 }"
      routerLinkActive="active"
      >新闻</a
    >
               
  • 2、组件中获取路由参数
    import { ActivatedRoute } from '@angular/router';
    
    export class NewsComponent implements OnInit, OnDestroy {
      public sub: any;
      constructor(private readonly route: ActivatedRoute) {}
    
      ngOnInit() {
        this.sub = this.route.queryParams.subscribe(data => {
          console.log(data);
        });
      }
    
      ngOnDestroy() {
        this.sub.unsubscribe();
      }
    }
               

六、在

js

中路由跳转

  • 1、不带参数的跳转
    import { Router } from '@angular/router';
    
    export class DetailComponent implements OnInit, OnDestroy {
      private sub: any;
      constructor(private readonly router: Router) {}
    
      public goHome() {
        this.router.navigate(['/home']);
      }
    }
               
  • 2、带参数的跳转(动态路由的方式)
    import { ActivatedRoute, Router } from '@angular/router';
    
    export class NewsComponent implements OnInit, OnDestroy {
      constructor(private readonly router: Router) {}
      public detail(): void {
        this.router.navigate(['/news', '2']);
      }
    }
               
  • 3、带

    query

    参数的跳转
    import { ActivatedRoute, Router, NavigationExtras } from '@angular/router';
    
    ...
    public goHome() {
      const navigationExtras: NavigationExtras = {
        // query参数
        queryParams: {
          name: 'hello',
          age: 20
        },
        fragment: 'aaa' // 锚点
      };
      this.router.navigate(['/home'], navigationExtras);
    }
               

七、路由的嵌套

  • 1、配置路由
    const routes: Routes = [
      {
        path: 'home',
        component: HomeComponent,
        children: [
          {
            path: 'add',
            component: AddComponent
          },
          {
            path: 'edit',
            component: EditComponent
          }
        ]
      },
      ...
    ]
               
  • 2、配置路由的跳转
    <p>
      <a [routerLink]="['/home/add']" routerLinkActive="active">添加内容</a>
    </p>
    <p>
      <a [routerLink]="['/home/edit']" routerLinkActive="active">编辑内容</a>
    </p>
               

八、路由与懒加载模块

  • 1、创建两个

    module

    和对应的组件
    ng g m pages/home --routing # 创建带路由的模块
    ng g m pages/user --routing
    
    # 创建组件
    ng g c pages/home
    ng g c pages/user
    ng g c pages/user/login
    ng g c pages/user/components/login
    ng g c pages/user/components/infomation
               
  • 2、主路由
    const routes: Routes = [
      {
        path: '',
        redirectTo: 'home',
        pathMatch: 'full'
      },
      {
        path: 'home',
        loadChildren: './pages/home/home.module#HomeModule'
      },
      {
        path: 'userInfo',
        loadChildren: './pages/user/user.module#UserModule'
      },
      {
        path: '**',
        loadChildren: './pages/home/home.module#HomeModule'
      }
    ];
               
  • 2、

    home

    的路由
    const routes: Routes = [
      {
        path: '',
        redirectTo: 'index',
        pathMatch: 'full'
      },
      {
        path: 'index',
        component: HomeComponent
      },
      {
        path: '**',
        redirectTo: 'index',
        pathMatch: 'full'
      }
    ];
               
  • 3、用户的路由
    const routes: Routes = [
      {
        path: '',
        redirectTo: 'user',
        pathMatch: 'full'
      },
      {
        path: 'user',
        component: UserComponent,
        children: [
          {
            path: 'login',
            component: LoginComponent
          },
          {
            path: 'user_info',
            component: InfomationComponent
          }
        ]
      },
      {
        path: '**',
        redirectTo: 'user',
        pathMatch: 'full'
      }
    ];
               

九、模块的预加载

上面对模块进行了懒加载,那么进入页面后不会全部加载出来,需要用户点击当页面后才会加载当前的数据,但是这样往往有个弊端(有些数据一开始是没有的,需要等待下才会出现)。为了解决这个等待,我们可以进行预加载
  • 1、方式一、简单粗暴的方法(直接在根路由下使用

    PreloadAllModules

    默认是

    NoPreloading

    )
    import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
    
    @NgModule({
      imports: [
        RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
      ],
      exports: [RouterModule]
    })
    export class AppRoutingModule {}
               
  • 2、方式二、根据自己配置去预加载对应的模块
    • 配置自己需要预加载的路由
      const routes: Routes = [
        {
          path: 'home',
          loadChildren: './pages/home/home.module#HomeModule',
          data: { preload: true }
        },
        {
          path: 'userInfo',
          loadChildren: './pages/user/user.module#UserModule',
          data: { preload: true }
        }
      ];
                 
    • 自己创建一个

      my-preloading-strategy.ts

      import { Route, PreloadingStrategy } from '@angular/router';
      import { Observable, of } from 'rxjs';
      
      export class MyPreloadingStrategy implements PreloadingStrategy {
        preload(route: Route, fn: () => Observable<any>): Observable<any> {
          return route.data && route.data.preload ? fn() : of(null);
        }
      }
                 
    • 3、在根模块中注入服务中
      import { MyPreloadingStrategy } from './common/my-preloading-strategy';
      
      /* @NgModule接受一个元数据对象,告诉angular如何编译和启动应用 */
      @NgModule({
        declarations: [AppComponent], // 引入当前项目运行的组件、指令、管道
        imports: [BrowserModule, AppRoutingModule, HomeModule, UserModule], // 引入当前模块运行依赖别的模块
        exports: [], // 对外暴露出去的
        providers: [MyPreloadingStrategy], // 定义的服务
        bootstrap: [AppComponent] // 指定应用的主视图
      })
      export class AppModule {}
                 
    • 4、在根路由中使用
      @NgModule({
        imports: [
          RouterModule.forRoot(routes, {
            preloadingStrategy: MyPreloadingStrategy
          })
        ],
        exports: [RouterModule]
      })
      export class AppRoutingModule {}
                 

十、使用

Location

模块返回到上一个菜单

  • 1、导包
    import { Location } from '@angular/common'
               
  • 2、使用
    // 返回上一级菜单
    private goback(): void {
      this.location.back();
    }
               

十一、代码下载地址