Angular/router 的基本了解

394 阅读3分钟

angular的路由router

初始化工作

  1. 在app文件之下创建app-routing.module.ts文件
ng new my-routing --routing // 新建项目并生成路由
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// 导入路由模块
import { RouterModule, Routes } from '@angular/router';

// 导入组件
import { DashboardComponent } from './dashboard/dashboard.component';

// 创建路由对象
const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
];

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }


/**
 * 首先,app-routing.module.ts 会导入 RouterModule 和 Routes,以便该应用具有路由功能。配置好路由后,接着导入 HeroesComponent,它将告诉路由器要去什么地方。
   注意,对 CommonModule 的引用和 declarations 数组不是必要的,因此它们不再是 AppRoutingModule 的一部分。以下各节将详细介绍 AppRoutingModule 的其余部分。
 */



  1. 在app.module.ts之中引入AppRoutingModule模块并注册

/* 引入 */
import { AppRoutingModule } from './app-routing.
@NgModule({
  // 组件注册
  declarations: [
    AppComponent,
  ],
  // angular内置模块,使用时需要手动引入
  imports: [
    BrowserModule,
    AppRoutingModule, // 注入
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

子路由

const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: 
  DashboardComponent ,children:[
   { path: 'home', component: HomeComponent },{ path: 'todo', component: TodoComponent },
  ]},
];

menu目录的写法

<a [routerLink]="['home']">首页</a>
<a routerLink="/dashboard/todo">Todo</a>

路由对象router的解析

  1. ==使用的方式==

引入

import { Router } from '@angular/router';
constructor( private router: Router) { }

  1. ==跳转==

navigateByUrl

/* 
定义:基于所提供的 URL 进行导航,必须使用绝对路径
参数:url(string | UrlReee )、extras(一个包含一组属性的对象,它会修改导航策略)
返回值:返回一个Promise。当导航成功时,它会解析成true;导航失败或者出错时,它会解析成false
*/
// 路由a跳转到路由b
this.router.navigateByUrl('b');  // 正确。解析结果是 localhost:4200/b
this.router.navigateByUrl('./b');  // 错误。只能是绝对路径哦

// 路由b跳转到路由c
this.router.navigateByUrl('cascader', {});  // 解析结果是 localhost:4200/c

navigate

/* 
定义:基于所提供的命令数组和起点路由进行导航。 如果没有指定起点路由,则从根路由开始进行绝对导航
参数:commands(any[] )、extras
返回值:返回一个Promise。当导航成功时,它会解析成true;导航失败时,它会解析成false;导航出错时,它会拒绝(reject)

值得注意的点是,navigate的第一个参数必须是数组形式的即 any[]。
*/
this.router.navigate(['c']);  // 绝对路径。 localhost:4200/c
this.router.navigate(['./c']);  // 相对路径。 localhost:4200/c


  1. ==参数==

模板路由方式

第一种: 在路由上添加查询参数,定义路由未进行修改

  • 传参
<a  routerLink="./component-a" [queryParams]="{id:'1'}">跳转a组件</a>
<!-- 页面地址://localhost:4200/router-study/component-a?id=1
 -->

 <a [routerLink]="['./component-a' ,{id:'2'}]" routerLinkActive="active">跳转a组件</a>
<!-- 页面地址 http://localhost:4200/router-study/component-a;id=2
 -->

  • 接收参数
 id: string = ''
constructor(public activeRoute: ActivatedRoute) {
}

ngOnInit(): void {
  this.activeRoute.queryParams.subscribe(res => {
      this.id = res['id']
    }
  )
     this.activeRoute.params.subscribe(res => {
      this.id = res?.id
    })
}

第二种: 动态路由,定义路由进行修改

  • 传参
<!--   {path: 'component-a/:id', component: ComponentAComponent}
 -->

  <a [routerLink]="['./component-a' ,'2']" routerLinkActive="active">跳转a组件</a>
<!-- 页面地址 http://localhost:4200/router-study/component-a/2
 -->

  • 接收参数
this.activeRoute.params.subscribe(res => {
     this.id = res?.id
   })

通过方法进行跳转传参

第一种:在路由上添加查询参数

  • 传参
this.router.navigate(['component-b',{id:'3'}] , {relativeTo: this.activeRoute}).then(r => console.log(r))
// http://localhost:4200/router-study/component-b;id=3

  • 接收参数
// 01
this.activateRoute.params.subscribe(res => {
  this.id = res['id']
})
// 02
if (this.activateRoute.snapshot.paramMap.get('id')) {
  this.id = this.activateRoute.snapshot.paramMap.get('id')
}

第二种 动态路由 定义路由进行修改

  • 传参
//  {path: 'component-b/:id', component: ComponentBComponent}
  this.router.navigate(['component-b','3'] , {relativeTo: this.activeRoute}).then(r => console.log(r))
// http://localhost:4200/router-study/component-b/3


  • 接收参数
// 01
this.activateRoute.params.subscribe(res => {
   this.id = res['id']
 })
// 02
 if (this.activateRoute.snapshot.paramMap.get('id')) {
   this.id = this.activateRoute.snapshot.paramMap.get('id')
 }

功能模块化并设置延迟加载

  1. 指令创建路由模块进行路由懒加载的设置
ng g m login --routing

  1. 路由模块的懒加载
const routes: Routes = [
    // 通过import 进行为路由功能模块的懒加载
  {
    path: 'items',
    loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)
  }
];

const routes: Routes = [
    // 在功能模块之中指向发自己
  {
    path: '',
    component: ItemsComponent,
    children:[
        {}, // 功能模块的子目录路由
    ]
  }
];

预先载入资料 Resolve

  1. 指令
ng g r login

详情:[blog.talllkai.com/Angular/202…]

实现路由进度条的加载动画

文档:[blog.talllkai.com/Angular/202…] 视频:[www.youtube.com/watch?v=jCL…]

路由守卫

  1. 指令 ng g g auth