iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > node.js >angular路由模块怎么用
  • 618
分享到

angular路由模块怎么用

2024-04-02 19:04:59 618人浏览 独家记忆
摘要

这篇文章主要讲解了“angular路由模块怎么用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“angular路由模块怎么用”吧!在 Angular 中,路由

这篇文章主要讲解了“angular路由模块怎么用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“angular路由模块怎么用”吧!

angular路由模块怎么用

在 Angular 中,路由是以模块为单位的,每个模块都可以有自己的路由。

快速上手


1、创建页面组件、Layout 组件以及 Navigation 组件,供路由使用

  • 创建首页页面组件ng g c pages/home

  • 创建关于我们页面组件ng g c pages/about

  • 创建布局组件ng g c pages/layout

  • 创建导航组件ng g c pages/navigation

2、创建路由规则

// app.module.ts
import { Routes } from "@angular/router"

const routes: Routes = [
  {
    path: "home",
    component: HomeComponent
  },
  {
    path: "about",
    component: AboutComponent
  }
]

3、引入路由模块并启动

// app.module.ts
import { RouterModule, Routes } from "@angular/router"

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true })],
})
export class AppModule {}

4、添加路由插座

<!-- 路由插座即占位组件 匹配到的路由组件将会显示在这个地方 -->
<router-outlet></router-outlet>

5、在导航组件中定义链接

<a routerLink="/home">首页</a>
<a routerLink="/about">关于我们</a>

匹配规则


1、重定向

const routes: Routes = [
  {
    path: "home",
    component: HomeComponent
  },
  {
    path: "about",
    component: AboutComponent
  },
  {
    path: "",
    // 重定向
    redirectTo: "home",
    // 完全匹配
    pathMatch: "full"
  }
]

2、404 页面

const routes: Routes = [
  {
    path: "home",
    component: HomeComponent
  },
  {
    path: "about",
    component: AboutComponent
  },
  {
    path: "**",
    component: NotFoundComponent
  }
]

路由传参


1、查询参数

<a routerLink="/about" [queryParams]="{ name: 'kitty' }">关于我们</a>
import { ActivatedRoute } from "@angular/router"

export class AboutComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  nGonInit(): void {
    this.route.queryParamMap.subscribe(query => {
      query.get("name")
    })
  }
}

2、动态参数

const routes: Routes = [
  {
    path: "home",
    component: HomeComponent
  },
  {
    path: "about/:name",
    component: AboutComponent
  }
]
<a [routerLink]="['/about', 'zhangsan']">关于我们</a>
import { ActivatedRoute } from "@angular/router"

export class AboutComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.route.paramMap.subscribe(params => {
      params.get("name")
    })
  }
}

路由嵌套


路由嵌套指的是如何定义子级路由

const routes: Routes = [
  {
    path: "about",
    component: AboutComponent,
    children: [
      {
        path: "introduce",
        component: IntroduceComponent
      },
      {
        path: "history",
        component: HistoryComponent
      }
    ]
  }
]
<!-- about.component.html -->
<app-layout>
  <p>about works!</p>
  <a routerLink="/about/introduce">公司简介</a>
  <a routerLink="/about/history">发展历史</a>
  <div>
    <router-outlet></router-outlet>
  </div>
</app-layout>

命名插座


将子级路由组件显示到不同的路由插座中。

{
  path: "about",
  component: AboutComponent,
  children: [
    {
      path: "introduce",
      component: IntroduceComponent,
      outlet: "left"
    },
    {
      path: "history",
      component: HistoryComponent,
      outlet: "right"
    }
  ]
}
<!-- about.component.html -->
<app-layout>
  <p>about works!</p>
  <router-outlet name="left"></router-outlet>
  <router-outlet name="right"></router-outlet>
</app-layout>
<a
    [routerLink]="[
      '/about',
      {
        outlets: {
          left: ['introduce'],
          right: ['history']
        }
      }
    ]"
    >关于我们
</a>

导航路由


<!-- app.component.html -->
 <button (click)="jump()">跳转到发展历史</button>
// app.component.ts
import { Router } from "@angular/router"

export class HomeComponent {
  constructor(private router: Router) {}
  jump() {
    this.router.navigate(["/about/history"], {
      queryParams: {
        name: "Kitty"
      }
    })
  }
}

路由模块


将根模块中的路由配置抽象成一个单独的路由模块,称之为根路由模块,然后在根模块中引入根路由模块。

import { NgModule } from "@angular/core"

import { HomeComponent } from "./pages/home/home.component"
import { NotFoundComponent } from "./pages/not-found/not-found.component"

const routes: Routes = [
  {
    path: "",
    component: HomeComponent
  },
  {
    path: "**",
    component: NotFoundComponent
  }
]

@NgModule({
  declarations: [],
  imports: [RouterModule.forRoot(routes, { useHash: true })],
  // 导出 Angular 路由功能模块,因为在根模块的根组件中使用了 RouterModule 模块中提供的路由插座组件
  exports: [RouterModule]
})
export class AppRoutingModule {}
import { BrowserModule } from "@angular/platfORM-browser"
import { NgModule } from "@angular/core"
import { AppComponent } from "./app.component"
import { AppRoutingModule } from "./app-routing.module"
import { HomeComponent } from "./pages/home/home.component"
import { NotFoundComponent } from "./pages/not-found/not-found.component"

@NgModule({
  declarations: [AppComponent,HomeComponent, NotFoundComponent],
  imports: [BrowserModule, AppRoutingModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

路由懒加载


路由懒加载是以模块为单位的。

1、创建用户模块 ng g m user --routing=true 一并创建该模块的路由模块

2、创建登录页面组件 ng g c user/pages/login

3、创建注册页面组件 ng g c user/pages/reGISter

4、配置用户模块的路由规则

import { NgModule } from "@angular/core"
import { Routes, RouterModule } from "@angular/router"
import { LoginComponent } from "./pages/login/login.component"
import { RegisterComponent } from "./pages/register/register.component"

const routes: Routes = [
  {
    path: "login",
    component: LoginComponent
  },
  {
    path: "register",
    component: RegisterComponent
  }
]

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class UserRoutingModule {}

5、将用户路由模块关联到主路由模块

// app-routing.module.ts
const routes: Routes = [
  {
    path: "user",
    loadChildren: () => import("./user/user.module").then(m => m.UserModule)
  }
]

6、在导航组件中添加访问链接

<a routerLink="/user/login">登录</a>
<a routerLink="/user/register">注册</a>

路由守卫


路由守卫会告诉路由是否允许导航到请求的路由。

路由守方法可以返回 booleanObservable <boolean>Promise <boolean>,它们在将来的某个时间点解析为布尔值。

1、CanActivate

检查用户是否可以访问某一个路由

CanActivate 为接口,路由守卫类要实现该接口,该接口规定类中需要有 canActivate 方法,方法决定是否允许访问目标路由。

路由可以应用多个守卫,所有守卫方法都允许,路由才被允许访问,有一个守卫方法不允许,则路由不允许被访问。

创建路由守卫:ng g guard guards/auth

import { Injectable } from "@angular/core"
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from "@angular/router"
import { Observable } from "rxjs"

@Injectable({
  providedIn: "root"
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}
  canActivate(): boolean | UrlTree {
    // 用于实现跳转
    return this.router.createUrlTree(["/user/login"])
    // 禁止访问目标路由
    return false
    // 允许访问目标路由
    return true
  }
}
{
  path: "about",
  component: AboutComponent,
  canActivate: [AuthGuard]
}

2、CanActivateChild

检查用户是否方可访问某个子路由。

创建路由守卫:ng g guard guards/admin 注意:选择 CanActivateChild,需要将箭头移动到这个选项并且敲击空格确认选择。

import { Injectable } from "@angular/core"
import { CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from "@angular/router"
import { Observable } from "rxjs"

@Injectable({
  providedIn: "root"
})
export class AdminGuard implements CanActivateChild {
  canActivateChild(): boolean | UrlTree {
    return true
  }
}
{
  path: "about",
  component: AboutComponent,
  canActivateChild: [AdminGuard],
  children: [
    {
      path: "introduce",
      component: IntroduceComponent
    }
  ]
}

3、CanDeactivate

检查用户是否可以退出路由。

比如用户在表单中输入的内容没有保存,用户又要离开路由,此时可以调用该守卫提示用户。

import { Injectable } from "@angular/core"
import {
  CanDeactivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  UrlTree
} from "@angular/router"
import { Observable } from "rxjs"

export interface CanComponentLeave {
  canLeave: () => boolean
}

@Injectable({
  providedIn: "root"
})
export class UnsaveGuard implements CanDeactivate<CanComponentLeave> {
  canDeactivate(component: CanComponentLeave): boolean {
    if (component.canLeave()) {
      return true
    }
    return false
  }
}
{
  path: "",
  component: HomeComponent,
  canDeactivate: [UnsaveGuard]
}
import { CanComponentLeave } from "src/app/guards/unsave.guard"

export class HomeComponent implements CanComponentLeave {
  myForm: FormGroup = new FormGroup({
    username: new FormControl()
  })
  canLeave(): boolean {
    if (this.myForm.dirty) {
      if (window.confirm("有数据未保存, 确定要离开吗")) {
        return true
      } else {
        return false
      }
    }
    return true
  }

4、Resolve

允许在进入路由之前先获取数据,待数据获取完成之后再进入路由。

ng g resolver <name>

import { Injectable } from "@angular/core"
import { Resolve } from "@angular/router"

type returnType = Promise<{ name: string }>

@Injectable({
  providedIn: "root"
})
export class ResolveGuard implements Resolve<returnType> {
  resolve(): returnType {
    return new Promise(function (resolve) {
      setTimeout(() => {
        resolve({ name: "张三" })
      }, 2000)
    })
  }
}
{
   path: "",
   component: HomeComponent,
   resolve: {
     user: ResolveGuard
   }
}
export class HomeComponent {
  constructor(private route: ActivatedRoute) {}
  ngOnInit(): void {
    console.log(this.route.snapshot.data.user)
  }
}

感谢各位的阅读,以上就是“angular路由模块怎么用”的内容了,经过本文的学习后,相信大家对angular路由模块怎么用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

--结束END--

本文标题: angular路由模块怎么用

本文链接: https://www.lsjlt.com/news/97851.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • angular路由模块怎么用
    这篇文章主要讲解了“angular路由模块怎么用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“angular路由模块怎么用”吧!在 Angular 中,路由...
    99+
    2024-04-02
  • 如何使用路由延迟加载Angular模块
    这篇文章主要介绍了如何使用路由延迟加载Angular模块,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。Angular 非常模块化,模块化的一...
    99+
    2024-04-02
  • Angular中路由有什么用
    这篇文章将为大家详细讲解有关Angular中路由有什么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。路由简介路由是实现单页面应用的一种方式,通过监听hash或者hist...
    99+
    2024-04-02
  • angular中的默认路由怎么用
    本篇内容介绍了“angular中的默认路由怎么用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!0.前言前一段时间折腾angular的路由折腾...
    99+
    2023-06-29
  • Node中的Express和路由模块怎么使用
    今天小编给大家分享一下Node中的Express和路由模块怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。Expres...
    99+
    2023-07-05
  • Angular路由的基本用法是什么
    这篇文章主要讲解了“Angular路由的基本用法是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Angular路由的基本用法是什么”吧!环境:Angul...
    99+
    2024-04-02
  • Remix路由模块输出对象loader函数怎么使用
    本篇内容介绍了“Remix路由模块输出对象loader函数怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!主要内容Remix load...
    99+
    2023-07-05
  • Remix路由模块输出对象handle函数怎么使用
    这篇“Remix路由模块输出对象handle函数怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Remix路由模块输出...
    99+
    2023-07-06
  • laravel8多模块、多应用和多应用路由
    1、安装多应用模块 composer require nwidart/laravel-modules 2、执行命令,config文件夹下生成一个modules.php配置文件 php artisan ...
    99+
    2023-09-01
    php nginx laravel8 laravel
  • Angular中是如何使用路由的
    这篇文章主要介绍“Angular中是如何使用路由的”,在日常操作中,相信很多人在Angular中是如何使用路由的问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Angular中...
    99+
    2024-04-02
  • Laravel8路由模块新增missing方法是什么
    这篇文章主要介绍了Laravel8路由模块新增missing方法是什么,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。Laravel 8.26.0 版本及以上,在路由模块新增了...
    99+
    2023-06-14
  • Angular中路由及其用法的示例
    这篇文章主要介绍了Angular中路由及其用法的示例,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。一、 Angular 创建一个默认带路由的项目命令创建项目ng new ng...
    99+
    2023-06-06
  • Angular中路由守卫的使用示例
    这篇文章主要介绍了Angular中路由守卫的使用示例,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。一、路由守卫当用户满足一定条件才被允许进入或者离开一个路由。路由守卫场景:只...
    99+
    2023-06-06
  • angular的HttpClientModule模块如何使用
    这篇文章主要介绍“angular的HttpClientModule模块如何使用”,在日常操作中,相信很多人在angular的HttpClientModule模块如何使用问题上存在疑惑,小编查阅了各式资料,整...
    99+
    2024-04-02
  • Angular中NgModule模块和延迟加载模块的用法
    这篇文章主要介绍“Angular中NgModule模块和延迟加载模块的用法”,在日常操作中,相信很多人在Angular中NgModule模块和延迟加载模块的用法问题上存在疑惑,小编查阅了各式资料,整理出简单...
    99+
    2024-04-02
  • NodeJS中怎么模拟WebApi路由
    本篇文章给大家分享的是有关NodeJS中怎么模拟WebApi路由,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。第一步,先设置controlle...
    99+
    2024-04-02
  • Angular中如何使用HttpClientModule模块
    这篇文章主要介绍Angular中如何使用HttpClientModule模块,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!该模块用于发送 Http 请求,用于发送请求的方法都返回 O...
    99+
    2024-04-02
  • Remix 路由模块输出对象handle函数
    目录正文在哪里可以定义 handle?在根路由定义在页面 _index 路由中与 useMatch 一起match 数组使用场景正文 Remix handle 函数是一个有用的对外...
    99+
    2023-05-15
    Remix 路由模块handle Remix handle函数
  • Angular路由基本使用方法有哪些
    这篇文章主要讲解了“Angular路由基本使用方法有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Angular路由基本使用方法有哪些”吧!1. 摘要简单来说地址栏中,不同的地址(URL...
    99+
    2023-07-04
  • Angular路由复用策略的示例分析
    这篇文章主要介绍了Angular路由复用策略的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。一、引言路由在执行过程中对组件无状态操作...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作