Angular 路由用法小记 | 更文挑战第4天

515 阅读2分钟

这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战

什么是 Routes ?

它是一组路由的配置信息,均包含以下配置:

export declare type Routes = Route[];

export interface Route {
    path?: string;
    pathMatch?: string;
    matcher?: UrlMatcher;
    component?: Type<any>;
    redirectTo?: string;
    outlet?: string;
    canActivate?: any[];
    canActivateChild?: any[];
    canDeactivate?: any[];
    canLoad?: any[];
    data?: Data;
    resolve?: ResolveData;
    children?: Routes;
    loadChildren?: LoadChildren;
    runGuardsAndResolvers?: RunGuardsAndResolvers;
}
  • path: 路径
path: 'signin'

它是一个用Angular路由器去匹配url对应关键词的字符串。
path为 signin 那么对应的 url 是.../signin

  • pathMatch: 路径匹配规则
pathMatch : 'prefix' // 默认的
pathMatch : 'full' 

prefix(前缀)是默认的,会去匹配url是否含有path字段,如果有则进行重定向。 full(完整的),加上他会看path和路径是否完全一致,一致的话则重定向。

  • matcher: 定义路径匹配的自定义策略,并取代路径和路径匹配规则
  • component: 需要渲染的组件
  • redirectTo: 重定向到的路由地址
  • outlet: 一个路由对应多个组件
// 路由
{ path: 'news', outlet: 'outlet1', component: demo1Component },
{ path: 'news', outlet: 'outlet2', component: demo2Component },
//组件里面
<router-outlet name="outlet1"></router-outlet>
<router-outlet name="outlet2"></router-outlet>
  • canActivate: 控制是否允许进入路由

获取当前路由

假设有个地址为 www.momomo.com/#/pages/user?id=123

1. 使用Router获取当前路由的URl

import {  Router } from '@angular/router';

export class xxxx {
    constructor(
        private router: Router
    ){
        const urlWithParam = this.router.url; // /pages/user?id=123
    }
}

router.url获取到的是路由和参数

2. 使用ActivatedRoute获取路由上的数据

import { ActivatedRoute } from '@angular/router';

export class xxxx {
    constructor(
        private activatedRoute: ActivatedRoute,
    ){
        // 获取当前路由的其他数据
        this.activatedRoute.data.subscribe(res => console.log(res));
    }
}

如何重载某个路由?

redirectTo(uri:string){
   this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=> this.router.navigate([uri]));
}

this.redirectTo('//place your uri here');

this.router.navigateByUrl('/', {skipLocationChange: true}): 首先用navigateByUrl跳转到一个其他路由/,并且{skipLocationChange: true}url不变化,再跳转到你的目标url。

需要注意的是,在路由配置中/和你的目标url如果是一个则不会起作用。

如routing.ts

export const PagesRouting: Routes = [
  { path: '', redirectTo: 'cat', pathMatch: 'full' },
  {
    path: 'cat',
    component: CatComponent,
  },
    {
    path: 'dog',
    component: DogComponent,
  },
  { path: '**', redirectTo: 'cat' },
];

如果在CatComponent中想重载该路由,

this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=> this.router.navigate(['/cat']));

不会起作用,因为'/'会被重定向到'cat',因此需要写一个其他路由

this.router.navigateByUrl('/dog', {skipLocationChange: true}).then(()=> this.router.navigate(['/cat']));

js刷新页面方法

1. reload() 方法

该类似于你浏览器上的刷新页面按钮。

location.reload();

2. replace() 方法

用一个新文档取代当前文档

 window.location.replace("your_uri")

更多用法更新于 github