Home > Web Front-end > JS Tutorial > body text

Deep dive into routing in Angular

青灯夜游
Release: 2021-09-07 11:30:06
forward
2399 people have browsed it

What is routing? This article will give you an in-depth understanding of routing in Angular, I hope it will be helpful to you!

Deep dive into routing in Angular

Routing introduction

Routing is a way to implement single-page applications, by listening to hash or Changes in history, rendering different components, play a role in local updates, avoiding requesting data from the server every time the URL changes. [Related tutorial recommendations: "angular tutorial"]

Routing configuration

Configure the routing module: approuter.module. Introduce the modified module into 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 { }
Copy after login

app.module.ts:

imports: [ ApprouterModule ]
Copy after login

Redirect route:

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

Wildcard routing:

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

Route lazy loading:

Configuring the lazy loading module can make the first screen The rendering speed is faster, and the corresponding module will only change when you click the lazy loading route.

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

Lazy loading module routing configuration:

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 { }
Copy after login

Lazy loading module routing navigation:

<a [routerLink]="[ &#39;LoadOne&#39; ]">LoadOne</a>
<a [routerLink]="[ &#39;LoadTwo&#39; ]">LoadTwo</a>
<router-outlet></router-outlet>
Copy after login

Route parameter passing:

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

Get route passing parameters:

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"]);
    }

}
Copy after login

The queryParams parameter is passed by value, and the parameter acquisition is also through the dependency injection of the activated route

<!-- 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; }); -->
Copy after login

Route guards: canActivate, canDeactivate, resolve, canLoad

The routing guard will return a value. If true is returned, execution continues, false prevents the behavior, and UrlTree navigates to the new route. The route guard may navigate to other routes, in which case it should return false. The route guard may depend on the server's value Decide whether to navigate, so you can also return Promise or Observable, and the route will wait The returned value is true or false. canActivate navigates to a route. canActivateChild navigates to a sub-route.

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 }
        // ]
    }
]
Copy after login
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);
    })
  }
}
Copy after login
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;
  }
}
Copy after login

parent.component.htmlRoute navigation:

<!-- 使用相对路径 -->
<a [routerLink]="[ &#39;./childOne&#39; ]">one</a>
<!-- 使用绝对路径 -->
<a [routerLink]="[ &#39;/parent/childTwo&#39; ]">two</a>
<router-outlet></router-outlet>
Copy after login

canDeactivate route to leave, prompting the user that the information has not been saved.

const routes: Routes = [
    { path: "first", component: FirstComponent, canDeactivate: [CanDeactivateGuard] }
]
Copy after login
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;
    }
}
Copy after login

Whether canLoad can enter the lazy loading module:

const routes: Routes = [
    {
        path: &#39;load&#39;,
        loadChildren: () => import(&#39;./load/load.module&#39;).then(m => m.LoadModule),
        // CanLoadModule如果返回false,模块里面的子路由都没有办法访问
        canLoad: [CanLoadModule]
    }
]
Copy after login
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;
      }
}
Copy after login

resolve configures how long it takes to enter the routing, and you can obtain the data before entering the routing to avoid the white screen

const routes: Routes = [
    { path: "resolve", component: ResolveDemoComponent, resolve: {detail: DetailResolver} 
]
Copy after login
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);
    })
  }
}
Copy after login

ResolveDemoComponent acquisition The value of resolve

constructor(private route: ActivatedRoute) { }
ngOnInit() {
    const detail = this.route.snapshot.data.detail;
    console.log(detail);
}
Copy after login

Listening to routing events:

constructor(private router: Router) {
    this.router.events.subscribe((event) => {
        // NavigationEnd,NavigationCancel,NavigationError,RoutesRecognized
        if (event instanceof NavigationStart) {
            console.log("NavigationStart");
        }
    })
}
Copy after login

For more programming-related knowledge, please visit:Programming Video! !

The above is the detailed content of Deep dive into routing in Angular. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template