Angular router

本文详细介绍了Angular路由的各个方面,包括基础用法、懒加载、嵌套路由、路由事件、路由参数传递、预加载策略、路由守卫以及如何使用多个router-outlet。通过对app.routing.module.ts配置文件的解析,展示了路由定义、懒加载开启和路由保护的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基础用法

app.routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';


const routes: Routes = [
	//定义路由数组
];

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

Route 定义

export declare interface Route {
    /**
     * The path to match against, a URL string that uses router matching notation.
     * Can be a wild card (`**`) that matches any URL (see Usage Notes below).
     * Default is "/" (the root path).
     */
    path?: string;
    /**
     * The path-matching strategy, one of 'prefix' or 'full'.
     * Default is 'prefix'.
     *
     * By default, the router checks URL elements from the left to see if the URL
     * matches a given  path, and stops when there is a match. For example,
     * '/team/11/user' matches 'team/:id'.
     *
     * The path-match strategy 'full' matches against the entire URL.
     * It is important to do this when redirecting empty-path routes.
     * Otherwise, because an empty path is a prefix of any URL,
     * the router would apply the redirect even when navigating
     * to the redirect destination, creating an endless loop.
     *
     */
    pathMatch?: string;
    /**
     * A URL-matching function to use as a custom strategy for path matching.
     * If present, supersedes `path` and `pathMatch`.
     */
    matcher?: UrlMatcher;
    /**
     * The component to instantiate when the path matches.
     * Can be empty if child routes specify components.
     */
    component?: Type<any>;
    /**
     * A URL to which to redirect when a the path matches.
     * Absolute if the URL begins with a slash (/), otherwise relative to the path URL.
     * When not present, router does not redirect.
     */
    redirectTo?: string;
    /**
     * Name of a `RouterOutlet` object where the component can be placed
     * when the path matches.
     */
    outlet?: string;
    /**
     * An array of dependency-injection tokens used to look up `CanActivate()`
     * handlers, in order to determine if the current user is allowed to
     * activate the component. By default, any user can activate.
     */
    canActivate?: any[];
    /**
     * An array of DI tokens used to look up `CanActivateChild()` handlers,
     * in order to determine if the current user is allowed to activate
     * a child of the component. By default, any user can activate a child.
     */
    canActivateChild?: any[];
    /**
     * An array of DI tokens used to look up `CanDeactivate()`
     * handlers, in order to determine if the current user is allowed to
     * deactivate the component. By default, any user can deactivate.
     *
     */
    canDeactivate?: any[];
    /**
     * An array of DI tokens used to look up `CanLoad()`
     * handlers, in order to determine if the current user is allowed to
     * load the component. By default, any user can load.
     */
    canLoad?: any[];
    /**
     * Additional developer-defined data provided to the component via
     * `ActivatedRoute`. By default, no additional data is passed.
     */
    data?: Data;
    /**
     * A map of DI tokens used to look up data resolvers. See `Resolve`.
     */
    resolve?: ResolveData;
    /**
     * An array of child `Route` objects that specifies a nested route
     * configuration.
     */
    children?: Routes;
    /**
     * A `LoadChildren` object specifying lazy-loaded child routes.
     */
    loadChildren?: LoadChildren;
    /**
     * Defines when guards and resolvers will be run. One of
     * - `paramsOrQueryParamsChange` : Run when query parameters change.
     * - `always` : Run on every execution.
     * By default, guards and resolvers run only when the matrix
     * parameters of the route change.
     */
    runGuardsAndResolvers?: RunGuardsAndResolvers;
}

懒加载

使用 Route 定义中的’loadChildren’ 开启懒加载模式

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

export const appRoutes:Routes=[
    {
        path:'自定义子路由path标示',
        loadChildren: () => import("子路由module文件相对路径").then(m => m.HomeModule)
    }
];

@NgModule({
    imports: [RouterModule.forRoot(appRoutes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

嵌套

使用 Route 定义中的’children’ 开启嵌套

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { 组件1Component类名 } from '组件1Component类相对路径';
import { 组件2Component类名 } from '组件2Component类相对路径';
import { 组件3Component类名 } from '组件3Component类相对路径';

export const homeRoutes:Routes = [
    {
        path: '',
        component: 组件1Component类名,
        children: [
            {
                path: '',
                redirectTo: 'path1',
                pathMatch: 'full'
            },
            {
                path: 'path2',
                component: 组件2Component类名
            },
            {
                path: 'path3',
                component: 组件3Component类名
            },
            {
                path: '**', // 星号路由必须为数组最后一位,即使不使用children
                component: 组件1Component类名
            }
        ]
    }
];

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

路由事件

/** 
Angular 路由事件:
NavigationStart
RoutesRecognized
RouteConfigLoadStart
RouteConfigLoadEnd
NavigationEnd
NavigationCancel
NavigationError
Scroll

Angular5新增:
GuardsCheckStart
ChildActivationStart
ActivationStart
GuardsCheckEnd
ResolveStart
ResolveEnd
ActivationEnd
ChildActivationEnd
*/
import { Component, OnInit } from '@angular/core';
import { Router,NavigationStart } from '@angular/router';

@Component({
  selector: 'duka',
  templateUrl: './duka.component.html',
  styleUrls: ['./duka.component.css']
})
export class DukaComponent implements OnInit {

  constructor(private router: Router) {

  }

  ngOnInit() {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationStart) {
		//do something
	  }
    });
  }
}

路由传参及代码路由

// html
<a [routerLink]="['path1','2020']">a1</a>
<a [routerLink]="['path2', {year: 2020, month: 5, city: 'Shanghai'}]">a2</a>

// ts
constructor(
	public activeRoute: ActivatedRoute) {

}

ngOnInit() {
	this.activeRoute.params.subscribe(
		(param) => {
			
		}
	);
}

//代码进行路由
this.router.navigate(["/path2"],{ queryParams: {year: 2020, month: 5, city: 'Shanghai'} });

预加载

// 1. 使用Angular内置的预加载策略: PreloadAllModules,NoPreloading
import { RouterModule, PreloadAllModules } from '@angular/router';

RouterModule.forRoot(appRoutes,{preloadingStrategy: PreloadAllModules})

// 2. 使用自定义预加载策略
// 2.1 自定义策略
import { Route,PreloadingStrategy } from '@angular/router';
import { Observable } from "rxjs";
import "rxjs/add/observable/of";

export class MyPreloadingStrategy implements PreloadingStrategy {
    preload(route: Route, fn: () => Observable<any>): Observable<any>{
        return route.data&&route.data.preload?fn():Observable.of(null);
    }
}

// 2.2 使用自定义策略
// 2.2.1 
export const homeRoutes:Routes = [
            {
                path: '',
                redirectTo: 'path1',
                pathMatch: 'full'
            },
            {
                path: 'path1',
                component: 组件1Component类名,
                data:{preload:true}
            },
            {
                path: 'path2',
                component: 组件2Component类名,
                data:{false}
            },
            {
                path: '**', // 星号路由必须为数组最后一位,即使不使用children
                component: 组件1Component类名
            }

];
// 2.2.2
import { MyPreloadingStrategy } from '自定义策略相对路径';

RouterModule.forRoot(appRoutes,{preloadingStrategy: MyPreloadingStrategy})

路由守卫

使用Route类中的canActivate

// 1. 定义守卫相关Service
import { Injectable } from '@angular/core';
import { CanLoad, CanActivate, CanActivateChild } from '@angular/router';

@Injectable()
export class DukaGuard implements CanLoad, CanActivate, CanActivateChild{

    constructor(){
    }

    canActivate(){
       //经过某些判断逻辑后,该函数需返回boolean
       // 1. do some judge
       // 2. return judge result
       return true;
    }
   
   ...
}

// 2. 使用定义的Service
import { DukaGuard } from '';
export const homeRoutes:Routes = [
            {
                path: '',
                redirectTo: 'path1',
                pathMatch: 'full'
            },
            {
                path: 'path1',
                component: 组件1Component类名,
                canActivate: [DukaGuard]
            },
            {
                path: '**', // 星号路由必须为数组最后一位,即使不使用children
                component: 组件1Component类名
            }

];

多个router-outlet

不常用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值