DevUI is an open source front-end solution for enterprise backend products. It advocates the design values of immersion, flexibility and simplicity, and advocates designers to serve the real needs and design for the majority of people, instead of sensationalism and eye-pleasing design. If you are working on a ToB tool-like product, DevUI is a great choice!

The introduction

Routing is a mechanism for mapping URL requests to specific code. It plays an important role in the module partitioning and information architecture of a site, and Angular has great routing capabilities. Take a look.

Route lazy loading

Angular dynamically loads module code based on routing, which is a great tool for performance optimization.

In order to speed up the rendering speed of the home page, we can design the following routes to keep the home page as simple and clean as possible:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'list',
        loadChildren: () => import('./components/list/list.module').then(m => m.ListModule),
      },
      {
        path: 'detail',
        loadChildren: () => import('./components/detail/detail.module').then(m => m.DetailModule),
      },
      ...
    ],
  },
];
Copy the code

The first page has a few simple static elements, while the rest of the page, such as lists, details, configuration modules, are loaded dynamically with loadChildren.

The effect is as follows:

The component-list-list-module-ngfactory. js file is loaded only when the /list route is accessed.

Routing guard

When we access or switch routes, the corresponding modules and components will be loaded. Route guards can be understood as hooks before and after loading routes. The most common ones are guards entering routes and guards leaving routes:

  • CanActivate enters the guard
  • CanDeactivate deactivates the guard

For example, we want to determine whether the user has permission to use the canActivate guard before entering the details page.

Adding a Route Guard

{ path: 'detail', loadChildren: () = > import ('. / components/detail/detail. The module '), then (m = > m. etailModule), / / routing guard canActivate: [AuthGuard],},Copy the code

Writing guard logic

Create a route guard module using CLI commands:

ng g guard auth
Copy the code

auth.guard.ts

import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable } from 'rxjs'; import { DetailService } from './detail.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor( private detailService: DetailService, ) {} canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return new Observable(observer => { // Authentication data from the backend interface asynchronous access this. DetailService. GetDetailAuth (). The subscribe ((hasPermission: Boolean) = > {observer. Next (hasPermission); observer.complete(); }); }); }}Copy the code

Obtain permission service

Service to obtain permission:

ng g s detail
Copy the code

detail.service.ts

import {Injectable} from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class DetailService { constructor( private http: HttpClient, ) { } getDetailAuth(): any { return this.http.get('/detail/auth'); }}Copy the code

The effect is as follows:

Because we have added guards to the /detail route, this page cannot be accessed either by switching from another route to the /detail route or by directly accessing the /detail route.

Dynamic routing parameters

There are many ways to take parameters in routing:

  • Take parameters in path
  • Takes parameters in queryString
  • Do not take parameters through links

Parameter in path

{
  path: 'user/:id',
  loadChildren: () => import('./components/user/user.module').then(m => m.UserModule),
},
Copy the code

Takes parameters in queryString

HTML and reference

<a [routerLink]="['/list']" [queryParams]="{id: '1'}">... </a>Copy the code

Ts the participation

this.router.navigate(['/list'],{ queryParams: { id: '1' });
Copy the code

Static parameters are passed through data

Note: Routing parameters passed through data can only be static

{ path: 'detail', loadChildren: () = > import ('. / components/detail/detail. The module '), then (m = > m. etailModule), / / static parameter data: {title: 'details'}},Copy the code

Pass dynamic parameters through resolve

Data can only pass static parameters, so I want to pass dynamic parameters from the background interface through routing, what should I do?

The answer is through the Resolve configuration.

{ path: 'detail', loadChildren: () = > import ('. / components/detail/detail. The module '), then (m = > m. etailModule), / / resolve dynamic routing parameters: {the detail: DetailResolver }, },Copy the code

Create a Resolver

detail.resolver.ts

import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { DetailService } from './detail.service'; @Injectable({ providedIn: 'root' }) export class DetailResolver implements Resolve<any> { constructor(private detailService: DetailService) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any { return this.detailService.getDetail(); }}Copy the code

Add a method to get detailed data in the service

detail.service.ts

import {Injectable} from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class DetailService { constructor( private http: HttpClient, ) { } getDetailAuth(): any { return this.http.get('/detail/auth'); } // Add getDetail(): any {return this.http.get('/detail'); }}Copy the code

Obtaining dynamic parameters

Create components

ng g c detial
Copy the code

detail.component.ts

import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-detail', templateUrl: './detail.component.html', styleUrls: ['./detail.component.scss'] }) export class DetailComponent implements OnInit { constructor( private route: ActivatedRoute,) {} ngOnInit () : void {/ / static parameters and obtain the same way const detail = this. The route. The snapshot. Data. The detail; console.log('detail:', detail); }}Copy the code

Welcome to devui-Official to discuss Angular technologies and front-end technologies.

Welcome to our DevUI component library and light up our little star 🌟 :

Github.com/devcloudfe/…

Also welcome to use DevUI’s newly released DevUI Admin system, out of the box, 10 minutes to build a beautiful atmosphere of the background management system!

Join us

We are DevUI team, welcome to come here and build elegant and efficient human-computer design/research and development system with us. Email: [email protected].

The text/DevUI Kagol

Previous articles are recommended

“Today is Children’s Day, the whole snake to play in the editor”

How to Insert dragons into an Editor?

Quill Rich Text Editor in Action

StepsGuide: A Component that Acts like a Follower

DevUI Admin V1.0 is released!