首页 web前端 js教程 深入了解Angular中的路由

深入了解Angular中的路由

Sep 07, 2021 am 11:30 AM
angular 路由

什么是路由?本篇文章带大家深入了解一下Angular中的路由,希望对大家有所帮助!

深入了解Angular中的路由

路由简介

路由是实现单页面应用的一种方式,通过监听hash或者history的变化,渲染不同的组件,起到局部更新的作用,避免每次URL变化都向服务器请求数据。【相关教程推荐:《angular教程》】

路由配置

配置路由模块:approuter.module.ts

const routes: Routes = [
    { path: "first", component: FirstComponent },
    { path: "parent", component: SecondComponent }
]
@NgModule({
    imports: [
        CommonModule,
        // RouterModule.forRoot方法会返回一个模块,其中包含配置好的Router服务
        // 提供者,以及路由库所需的其它提供者。
        RouterModule.forRoot(routes, {
            // enableTracing: true, // <-- debugging purposes only
            // 配置所有的模块预加载,也就是懒加载的模块,在系统空闲时,把懒加载模块加载进来
            // PreloadAllModules 策略不会加载被CanLoad守卫所保护的特性区。
            preloadingStrategy: PreloadAllModules
          })
    ],
    exports: [
        FirstComponent,
        SecondComponent,
        RouterModule
    ],
    declarations: [
        FirstComponent,
        SecondComponent
    ]
})
export class ApprouterModule { }
登录后复制

app.module.ts中引入改模块:

imports: [ ApprouterModule ]
登录后复制

重定向路由:

const routes: Routes = [
    { path: "", redirectTo: "first", pathMatch: "full" }
]
登录后复制

通配符路由:

const routes: Routes = [
    // 路由器会使用先到先得的策略来选择路由。 由于通配符路由是最不具体的那个,因此务必确保它是路由配置中的最后一个路由。
    { path: "**", component: NotFoundComponent }
]
登录后复制

路由懒加载:

配置懒加载模块可以使得首屏渲染速度更快,只有点击懒加载路由的时候,对应的模块才会更改。

const routes: Routes = [
    {
        path: &#39;load&#39;,
        loadChildren: () => import(&#39;./load/load.module&#39;).then(m => m.ListModule),
        // CanLoadModule如果返回false,模块里面的子路由都没有办法访问
        canLoad: [CanLoadModule]
    },
]
登录后复制

懒加载模块路由配置:

import { NgModule } from &#39;@angular/core&#39;;
import { CommonModule } from &#39;@angular/common&#39;;
import { LoadComponent } from &#39;./Load.component&#39;;
import { RouterModule, Routes } from &#39;@angular/router&#39;;
import { LoadTwoComponent } from &#39;../../../app/components/LoadTwo/LoadTwo.component&#39;;
import { LoadOneComponent } from &#39;../../../app/components/LoadOne/LoadOne.component&#39;;

const routes: Routes = [
    {
        path: "",
        component: LoadComponent,
        children: [
            { path: "LoadOne", component: LoadOneComponent },
            { path: "LoadTwo", component: LoadTwoComponent }
        ]
    },

]

@NgModule({
    imports: [
        CommonModule,
        //子模块使用forChild配置
        RouterModule.forChild(routes)
    ],

    declarations: [
        LoadComponent,
        LoadOneComponent,
        LoadTwoComponent
    ]
})
export class LoadModule { }
登录后复制

懒加载模块路由导航:

<a [routerLink]="[ &#39;LoadOne&#39; ]">LoadOne</a>
<a [routerLink]="[ &#39;LoadTwo&#39; ]">LoadTwo</a>
<router-outlet></router-outlet>
登录后复制

路由参数传递:

const routes: Routes = [
    { path: "second/:id", component: SecondComponent },
]
登录后复制
//routerLinkActive配置路由激活时的类
<a [routerLink]="[ &#39;/second&#39;, 12 ]" routerLinkActive="active">second</a>
登录后复制

获取路由传递的参数:

import { ActivatedRoute, ParamMap, Router } from &#39;@angular/router&#39;;
import { Component, OnInit } from &#39;@angular/core&#39;;
import { switchMap } from &#39;rxjs/operators&#39;;

@Component({
    selector: &#39;app-second&#39;,
    templateUrl: &#39;./second.component.html&#39;,
    styleUrls: [&#39;./second.component.scss&#39;]
})
export class SecondComponent implements OnInit {

    constructor(private activatedRoute: ActivatedRoute, private router: Router) { }

    ngOnInit() {

        console.log(this.activatedRoute.snapshot.params);  //{id: "12"}
        // console.log(this.activatedRoute);
        // 这种形式可以捕获到url输入 /second/18 然后点击<a [routerLink]="[ &#39;/second&#39;, 12 ]">second</a>   
        // 是可以捕获到的。上面那种是捕获不到的。因为不会触发ngOnInit,公用了一个组件实例。
        this.activatedRoute.paramMap.pipe(
            switchMap((params: ParamMap) => {
                console.log(params.get(&#39;id&#39;));
                return "param";
        })).subscribe(() => {

        })
    }
    gotoFirst() {
        this.router.navigate(["/first"]);
    }

}
登录后复制

queryParams参数传值,参数获取也是通过激活的路由的依赖注入

<!-- queryParams参数传值 -->
<a [routerLink]="[ &#39;/first&#39; ]" [queryParams]="{name: &#39;first&#39;}">first</a>   
<!-- ts中传值 -->
<!-- this.router.navigate([&#39;/first&#39;],{ queryParams: { name: &#39;first&#39; }); -->
登录后复制

路由守卫:canActivate,canDeactivate,resolve,canLoad

路由守卫会返回一个值,如果返回true继续执行,false阻止该行为,UrlTree导航到新的路由。 路由守卫可能会导航到其他的路由,这时候应该返回false。路由守卫可能会根据服务器的值来 决定是否进行导航,所以还可以返回Promise或 Observable,路由会等待 返回的值是true还是false。 canActivate导航到某路由。 canActivateChild导航到某子路由。

const routes: Routes = [
    {
        path: "parent",
        component: ParentComponent,
        canActivate: [AuthGuard],
        children: [
            // 无组件子路由
            {
                path: "",
                canActivateChild: [AuthGuardChild],
                children: [
                    { path: "childOne", component: ChildOneComponent },
                    { path: "childTwo", component: ChildTwoComponent }
                ]
            }
        ],
        // 有组件子路由
        // children: [
        //     { path: "childOne", component: ChildOneComponent },
        //     { path: "childTwo", component: ChildTwoComponent }
        // ]
    }
]
登录后复制
import { Injectable } from &#39;@angular/core&#39;;
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from &#39;@angular/router&#39;;

@Injectable({
  providedIn: &#39;root&#39;,
})
export class AuthGuard implements CanActivate {
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): any {
    // return true;
    // 返回Promise的情况
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve(true);
        }, 3000);
    })
  }
}
登录后复制
import { Injectable } from &#39;@angular/core&#39;;
import {
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  CanActivateChild
} from &#39;@angular/router&#39;;

@Injectable({
  providedIn: &#39;root&#39;,
})
export class AuthGuardChild implements CanActivateChild {
  constructor() {}


  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    return true;
  }
}
登录后复制

parent.component.html路由导航:

<!-- 使用相对路径 -->
<a [routerLink]="[ &#39;./childOne&#39; ]">one</a>
<!-- 使用绝对路径 -->
<a [routerLink]="[ &#39;/parent/childTwo&#39; ]">two</a>
<router-outlet></router-outlet>
登录后复制

canDeactivate路由离开,提示用户没有保存信息的情况。

const routes: Routes = [
    { path: "first", component: FirstComponent, canDeactivate: [CanDeactivateGuard] }
]
登录后复制
import { FirstComponent } from &#39;./components/first/first.component&#39;;
import { RouterStateSnapshot } from &#39;@angular/router&#39;;
import { ActivatedRouteSnapshot } from &#39;@angular/router&#39;;
import { Injectable } from &#39;@angular/core&#39;;
import { CanDeactivate } from &#39;@angular/router&#39;;

@Injectable({
    providedIn: &#39;root&#39;,
})
export class CanDeactivateGuard implements CanDeactivate<any> {
    canDeactivate(
        component: any,
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot
    ): boolean {
        // component获取到组件实例
        console.log(component.isLogin);
        return true;
    }
}
登录后复制

canLoad是否能进入懒加载模块:

const routes: Routes = [
    {
        path: &#39;load&#39;,
        loadChildren: () => import(&#39;./load/load.module&#39;).then(m => m.LoadModule),
        // CanLoadModule如果返回false,模块里面的子路由都没有办法访问
        canLoad: [CanLoadModule]
    }
]
登录后复制
import { Route } from &#39;@angular/compiler/src/core&#39;;
import { Injectable } from &#39;@angular/core&#39;;
import { CanLoad } from &#39;@angular/router&#39;;


@Injectable({
    providedIn: &#39;root&#39;,
})
export class CanLoadModule implements CanLoad {
    canLoad(route: Route): boolean {

        return true;
      }
}
登录后复制

resolve配置多久后可以进入路由,可以在进入路由前获取数据,避免白屏

const routes: Routes = [
    { path: "resolve", component: ResolveDemoComponent, resolve: {detail: DetailResolver} 
]
登录后复制
import { Injectable } from &#39;@angular/core&#39;;
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from &#39;@angular/router&#39;;

@Injectable({ providedIn: &#39;root&#39; })
export class DetailResolver implements Resolve<any> {

  constructor() { }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve("resolve data");
        }, 3000);
    })
  }
}
登录后复制

ResolveDemoComponent获取resolve的值

constructor(private route: ActivatedRoute) { }
ngOnInit() {
    const detail = this.route.snapshot.data.detail;
    console.log(detail);
}
登录后复制

监听路由事件:

constructor(private router: Router) {
    this.router.events.subscribe((event) => {
        // NavigationEnd,NavigationCancel,NavigationError,RoutesRecognized
        if (event instanceof NavigationStart) {
            console.log("NavigationStart");
        }
    })
}
登录后复制

更多编程相关知识,请访问:编程视频!!

以上是深入了解Angular中的路由的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它们
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何在Ubuntu 24.04上安装Angular 如何在Ubuntu 24.04上安装Angular Mar 23, 2024 pm 12:20 PM

Angular.js是一种可自由访问的JavaScript平台,用于创建动态应用程序。它允许您通过扩展HTML的语法作为模板语言,以快速、清晰地表示应用程序的各个方面。Angular.js提供了一系列工具,可帮助您编写、更新和测试代码。此外,它还提供了许多功能,如路由和表单管理。本指南将讨论在Ubuntu24上安装Angular的方法。首先,您需要安装Node.js。Node.js是一个基于ChromeV8引擎的JavaScript运行环境,可让您在服务器端运行JavaScript代码。要在Ub

在Slim框架中实现API路由的方法 在Slim框架中实现API路由的方法 Aug 02, 2023 pm 05:13 PM

在Slim框架中实现API路由的方法Slim是一款轻量级的PHP微型框架,它提供了一个简单而灵活的方式来构建Web应用程序。其中一个主要功能是实现API路由,使我们能够将不同的请求映射到相应的处理程序。本文将介绍如何在Slim框架中实现API路由,并提供一些代码示例。首先,我们需要安装Slim框架。可以通过Composer来安装最新版本的Slim。打开终端并

Java Apache Camel:打造灵活而高效的面向服务体系架构 Java Apache Camel:打造灵活而高效的面向服务体系架构 Feb 19, 2024 pm 04:12 PM

ApacheCamel是一个基于企业服务总线(ESB)的集成框架,它可以轻松地将不同的应用程序、服务和数据源集成在一起,从而实现复杂的业务流程自动化。ApacheCamel使用基于路由的配置方式,可以轻松地定义和管理集成流程。ApacheCamel的主要特点包括:灵活性:ApacheCamel可以轻松地与各种应用程序、服务和数据源集成。它支持多种协议,包括Http、JMS、SOAP、FTP等。高效性:ApacheCamel非常高效,它可以处理大量的消息。它使用异步消息传递机制,可以提高性能。可扩

Angular组件及其显示属性:了解非block默认值 Angular组件及其显示属性:了解非block默认值 Mar 15, 2024 pm 04:51 PM

Angular框架中组件的默认显示行为不是块级元素。这种设计选择促进了组件样式的封装,并鼓励开发人员有意识地定义每个组件的显示方式。通过显式设置CSS属性 display,Angular组件的显示可以完全控制,从而实现所需的布局和响应能力。

使用Angular和Node进行基于令牌的身份验证 使用Angular和Node进行基于令牌的身份验证 Sep 01, 2023 pm 02:01 PM

身份验证是任何Web应用程序中最重要的部分之一。本教程讨论基于令牌的身份验证系统以及它们与传统登录系统的区别。在本教程结束时,您将看到一个用Angular和Node.js编写的完整工作演示。传统身份验证系统在继续基于令牌的身份验证系统之前,让我们先看一下传统的身份验证系统。用户在登录表单中提供用户名和密码,然后点击登录。发出请求后,通过查询数据库在后端验证用户。如果请求有效,则使用从数据库中获取的用户信息创建会话,然后在响应头中返回会话信息,以便将会话ID存储在浏览器中。提供用于访问应用程序中受

如何在ThinkPHP6中使用路由 如何在ThinkPHP6中使用路由 Jun 20, 2023 pm 07:54 PM

ThinkPHP6是一款强大的PHP框架,拥有便捷的路由功能,可以轻松实现URL路由配置;同时,ThinkPHP6还支持多种路由模式,如GET、POST、PUT、DELETE等等。本文将介绍如何使用ThinkPHP6进行路由配置。一、ThinkPHP6路由模式GET方式:GET方式是用于获取数据的一种方式,常用于页面展示。在ThinkPHP6中,可以使用如下

如何在Vue项目中使用路由实现页面切换动画效果的定制? 如何在Vue项目中使用路由实现页面切换动画效果的定制? Jul 21, 2023 pm 02:37 PM

如何在Vue项目中使用路由实现页面切换动画效果的定制?引言:在Vue项目中,路由是我们经常使用的功能之一。通过路由可以实现页面之间的切换,提供了良好的用户体验。而为了让页面切换更加生动,我们可以通过定制动画效果实现。本文将介绍如何在Vue项目中使用路由实现页面切换动画效果的定制。创建Vue项目首先,我们需要创建一个Vue项目。可以使用VueCLI来快速搭建

PHP中灵活配置路由规则的实现方法和经验总结 PHP中灵活配置路由规则的实现方法和经验总结 Oct 15, 2023 pm 03:43 PM

PHP中灵活配置路由规则的实现方法和经验总结引言:在Web开发中,路由规则是非常重要的一部分,它决定了URL与具体的PHP脚本的对应关系。在传统的开发方式中,我们通常会在路由文件中配置各种URL规则,然后将URL与对应的脚本路径进行映射。但是,随着项目的复杂度增加和业务需求的变化,如果每个URL都需要手动配置,将会变得非常麻烦和不灵活。那么,在PHP中如何实

See all articles