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、方式一直接使用

    <a routerLink="home">首页</a>
    
  • 2、动态传递值的方式

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

三、路由选中的样式

<a routerLink="home" routerLinkActive="active">首页</a>

四、动态路由

  • 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();
    }
    

十一、代码下载地址

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值