深入了解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, // 

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

imports: [ ApprouterModule ]

登录后复制

重定向路由:

const routes: Routes = [    { path: "", redirectTo: "first", pathMatch: "full" }]

登录后复制

通配符路由:

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

登录后复制

路由懒加载:

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

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

登录后复制

懒加载模块路由配置:

import { NgModule } from '@angular/core';import { CommonModule } from '@angular/common';import { LoadComponent } from './Load.component';import { RouterModule, Routes } from '@angular/router';import { LoadTwoComponent } from '../../../app/components/LoadTwo/LoadTwo.component';import { LoadOneComponent } from '../../../app/components/LoadOne/LoadOne.component';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 { }

登录后复制

懒加载模块路由导航:

LoadOneLoadTwo

登录后复制

路由参数传递:

const routes: Routes = [    { path: "second/:id", component: SecondComponent },]

登录后复制

//routerLinkActive配置路由激活时的类second

登录后复制

获取路由传递的参数:

import { ActivatedRoute, ParamMap, Router } from '@angular/router';import { Component, OnInit } from '@angular/core';import { switchMap } from 'rxjs/operators';@Component({    selector: 'app-second',    templateUrl: './second.component.html',    styleUrls: ['./second.component.scss']})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 然后点击second           // 是可以捕获到的。上面那种是捕获不到的。因为不会触发ngOnInit,公用了一个组件实例。        this.activatedRoute.paramMap.pipe(            switchMap((params: ParamMap) => {                console.log(params.get('id'));                return "param";        })).subscribe(() => {        })    }    gotoFirst() {        this.router.navigate(["/first"]);    }}

登录后复制

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

first   

登录后复制

路由守卫: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 '@angular/core';import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';@Injectable({  providedIn: 'root',})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 '@angular/core';import {  ActivatedRouteSnapshot,  RouterStateSnapshot,  CanActivateChild} from '@angular/router';@Injectable({  providedIn: 'root',})export class AuthGuardChild implements CanActivateChild {  constructor() {}  canActivateChild(    route: ActivatedRouteSnapshot,    state: RouterStateSnapshot): boolean {    return true;  }}

登录后复制

parent.component.html路由导航:

onetwo

登录后复制

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

const routes: Routes = [    { path: "first", component: FirstComponent, canDeactivate: [CanDeactivateGuard] }]

登录后复制

import { FirstComponent } from './components/first/first.component';import { RouterStateSnapshot } from '@angular/router';import { ActivatedRouteSnapshot } from '@angular/router';import { Injectable } from '@angular/core';import { CanDeactivate } from '@angular/router';@Injectable({    providedIn: 'root',})export class CanDeactivateGuard implements CanDeactivate {    canDeactivate(        component: any,        route: ActivatedRouteSnapshot,        state: RouterStateSnapshot    ): boolean {        // component获取到组件实例        console.log(component.isLogin);        return true;    }}

登录后复制

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

const routes: Routes = [    {        path: 'load',        loadChildren: () => import('./load/load.module').then(m => m.LoadModule),        // CanLoadModule如果返回false,模块里面的子路由都没有办法访问        canLoad: [CanLoadModule]    }]

登录后复制

import { Route } from '@angular/compiler/src/core';import { Injectable } from '@angular/core';import { CanLoad } from '@angular/router';@Injectable({    providedIn: 'root',})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 '@angular/core';import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';@Injectable({ providedIn: 'root' })export class DetailResolver implements Resolve {  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中的路由的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2708235.html

(0)
上一篇 2025年3月7日 20:19:17
下一篇 2025年3月1日 12:30:41

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • 深入浅析Angular中的依赖注入

    什么是依赖注入?本篇文章带大家了解一下angular中的依赖注入,希望对大家有所帮助! 依赖注入概念: 维基百科对依赖注入的解释:在软件工程中,依赖注入是实现控制反转的一种软件设计模式,一个依赖是一个被其他对象(client)调用的对象(服…

    2025年3月7日
    200
  • 聊聊Angular中常用的错误处理方式

    本篇文章带大家深入了解一下angular中常用的错误处理方式,希望对大家有所帮助! 错误处理是编写代码经常遇见的并且必须处理的需求,很多时候处理异常的逻辑是为了避免程序的崩溃,本文将简单介绍Angular处理异常的方式。【相关教程推荐:《a…

    2025年3月7日
    200
  • 带你了解Angular10中的双向绑定

    下面本篇文章带大家了解一下双向绑定,看看angular中两种类型的双向绑定,希望对大家有所帮助! 前面我们了解了属性绑定、事件绑定以及输入和输出的使用,是时候了解双向绑定了。本节,我们将利用@Input()和@Output()来了解下双向绑…

    2025年3月7日 编程技术
    200
  • 浅析Angular中什么是ngModule

    什么是ngmodule?本篇文章带给大家简单了解一下angular语法,介绍一下angular中的ngmodule,希望对大家有所帮助! 作为Angular10教程,在我的理解中,angular相较于VUE,它的模块化做得更好,这样使代码结…

    2025年3月7日
    200
  • 聊聊Angular+Service如何改进日志功能

    如何改善angular的日志使用方式?下面本篇文章给大家介绍一下使用angular中的service管理控制台输出,改进日志功能的方法,希望对大家有所帮助! 改善在Angular 应用中的日志使用方式 Angular是一个非常受欢迎的开发框…

    2025年3月7日 编程技术
    200
  • 深入浅析Angular中的指令、管道和服务

    angular中什么是指令、管道、服务?下面本篇文章带大家了解一下angular中的指令、管道和服务,希望对大家有所帮助! 1. 指令 Directive 指令是 Angular 提供的操作 DOM 的途径。指令分为属性指令和结构指令。【相…

    2025年3月7日
    200
  • 带你了解Angular中的组件通讯和依赖注入

    angular组件间怎么进行通讯?依赖注入是什么?下面本篇文章带大家简单了解一下组件通讯的方法,并介绍一下依赖注入,希望对大家有所帮助! 1.  组件通讯 1.1  向组件内部传递数据 登录后复制 // favorite.component…

    2025年3月7日
    200
  • 浅析Angular中两种类型的Form表单

    本篇文章带大家了解一下angular中两种form表单,简单介绍一下它们的用法,希望对大家有所帮助! 在 Angular 中,表单有两种类型,分别为模板驱动和模型驱动。【相关教程推荐:《angular教程》】 1.  模板驱动 1.1  概…

    2025年3月7日 编程技术
    200
  • 深入了解Angular中的路由,如何快速上手?

    本篇文章带大家深入了解一下angular中的路由,看看快速上手的方法,介绍一下匹配规则、路由传参、路由嵌套、路由守卫等,希望对大家有所帮助! 在 Angular 中,路由是以模块为单位的,每个模块都可以有自己的路由。【相关教程推荐:《ang…

    2025年3月7日
    200
  • 深入浅析Angular中怎么使用动画

    本篇文章带大家了解一下angular 动画,希望对大家有所帮助!! 1.  状态 1.1  什么是状态 状态表示的是要进行运动的元素在运动的不同时期所呈现的样式。【相关教程推荐:《angular教程》】 1.2  状态的种类 在 Angul…

    2025年3月7日 编程技术
    200

发表回复

登录后才能评论