Angular 入门基础(第四篇) 路由的使用

97 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第4天。点击查看活动详情

配置路由

路由的配置参数如下:

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: 路径

用于 Angular 路由器去匹配 url 对应关键词的字符串。 如 path 为 login 那么对应的 url 是.../login

pathMatch: 路径匹配规则

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

{
  path: '',
  pathMatch: 'prefix', //default
}

matcher: 定义路径匹配的自定义策略,并取代路径和路径匹配规则

component: 需要渲染的组件

{
    path: 'user/:name',
    component: User
}

redirectTo: 重定向到的路由地址

{
    path: 'legacy/user/:name',
    redirectTo: 'user/:name'
}

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: 控制是否允许进入路由

{
    path: 'test',
    canActivate: [ CanAuthProvide ], // 可用于路由守卫
}

canActivate()返回 true,表示可以进入指定路由;否则停留到当前页面

canActivateChild:

canActivateChild 和 canActivate 用法类似,两者的区别在于前者会在其任意一个子路由变化的时候检测。

canDeactivate:

当页面数据未保存跳转监听使用 canDeactivate 实现

children: 子路由

loadChildren: 惰性加载

{
  path: 'lazy',
  loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule),
}

路由的基本用法

import { HomeComponent } from "./home/home.component";
import { NewsComponent } from "./news/news.component";
import { NewscontentComponent } from "./newscontent/newscontent.component";
const routes: Routes = [
  { path: "home", component: HomeComponent },
  { path: "news", component: NewsComponent },
  { path: "newscontent/:id", component: NewscontentComponent },
  {
    path: "",
    redirectTo: "/home",
    pathMatch: "full",
  },
];

父子路由

import { NewsaddComponent } from './components/newsadd/newsadd.component';
import { NewslistComponent } from './components/newslist/newslist.component';
const routes: Routes = [
  //匹配不到路由的时候加载的组件或者跳转的路由
  {
    path: '**', /*任意的路由*/
    component:HomeComponent
    redirectTo:'home'
  },
	{
	path: 'news',
	component:NewsComponent,
    children: [
        {
        path:'newslist',
        component:NewslistComponent
        },
        {
        path:'newsadd',
        component:NewsaddComponent
        }
	]
   }
];

loadChildren 配置懒加载

const routes: Routes = [
  {
    path: "widgets",
    loadChildren: () =>
      import("./widgets/widgets.module").then((m) => m.WidgetsModule),
  },
];

routerLink 跳转页面

<h1>
  <a routerLink="/home">首页</a>
  <a routerLink="/news">新闻</a>
</h1>

routerLinkActive 设置 routerLink 默认选中路由

<h1>
  <a routerLink="/home" routerLinkActive="active">首页</a>
  <a routerLink="/news" routerLinkActive="active">新闻</a>
</h1>

<h1>
  <a [routerLink]="[ '/home' ]" routerLinkActive="active">首页</a>
  <a [routerLink]="[ '/news' ]" routerLinkActive="active">新闻</a>
</h1>

配置动态路由

routerLink 跳转传值

<a [routerLink]="[ '/newscontent/',aid]">跳转到详情</a>
<a routerLink="/newscontent/{{aid}}">跳转到详情</a>

获取动态路由的值

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
@Component({
  selector: "app-data-v-relation",
  templateUrl: "./relation.component.html",
})
export class RelationComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    console.log(this.route.params);
    this.route.params.subscribe((data) => (this.id = data.id));
  }
}

get 路由和动态路由

get 传值跳转

<li *ngFor="let item of list;let key=index;">
  <!-- <a href="/newscontent?aid=123">{{key}}--{{item}}</a> -->
  <a [routerLink]="['/newscontent']" [queryParams]="{aid:key}"
    >{{key}}--{{item}}</a
  >
</li>

get 传值接收

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
@Component({
  selector: "app-data-v-relation",
  templateUrl: "./relation.component.html",
})
export class RelationComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.queryParams.subscribe((data) => {
      console.log(data);
    });
  }
}

配置动态路由

const routes: Routes = [
  {
    path: "newscontent/:aid",
    component: NewscontentComponent,
  },
];
<ul>
  <li *ngFor="let item of list;let key=index;">
    <a [routerLink]="[ '/newscontent/', key ]">{{key}}---{{item}}</a>
  </li>
</ul>

接收值

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";

@Component({
  selector: "app-data-v-relation",
  templateUrl: "./relation.component.html",
})
export class RelationComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.params.subscribe((data) => {
      console.log(data);
    });
  }
}

动态路由的 js 跳转

import { Router } from "@angular/router";
export class HomeComponent implements OnInit {
  constructor(private router: Router) {}
  ngOnInit() {}
  goNews() {
    this.router.navigate(["/news", hero.id]);
    this.router.navigate(["/news"]);
  }
}

路由 get 传值 js 跳转

定义一个 goNewsContent 方法执行跳转,用 NavigationExtras 配置传参

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

goNewsContent(){
	let navigationExtras: NavigationExtras = {
		queryParams: { 'session_id': '123' },
		fragment: 'anchor'
	};
	this.router.navigate(['/news'],navigationExtras);
}

获取 get 的传值

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
@Component({
  selector: "app-data-v-relation",
  templateUrl: "./relation.component.html",
})
export class RelationComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.queryParams.subscribe((data) => {
      console.log(data);
    });
  }
}