Home  >  Article  >  Web Front-end  >  A brief discussion on how to use routing in Angular?

A brief discussion on how to use routing in Angular?

青灯夜游
青灯夜游forward
2021-09-01 18:38:033070browse

How to use routing in Angular? This article will show you how to use routing in Angular and get you started quickly with Angular routing. I hope it will be helpful to you!

A brief discussion on how to use routing in Angular?

The concept of routing has been widely used in the front-end framework. I will not elaborate on the thoughts of routing. The application of routing is nothing more than nesting and passing parameters. More advanced functions such as lazy loading, preloading, and more advanced functions such as routing guards, etc. In this article, we will take a look at how to use routing in Angular. [Related tutorial recommendations: "angular tutorial"]

Please follow the structure in the picture to create our project

A brief discussion on how to use routing in Angular?

Create project & first-level module:

  • ng new angular-router-sample

  • ng g c pages/login

  • ng g c pages/home

  • ng g c pages/mine

Note: Components created through cli will be automatically registered.

Getting Started

1. Configure

in the html template of the App to configure routing jumps & routing exits (router- outlet)

<div>
  <a [routerLink]="[&#39;/login&#39;]">登陆</a>|
  <a [routerLink]="[&#39;/home&#39;]">首页</a>|
  <a [routerLink]="[&#39;/mine&#39;]">我的</a>
</div>
<!-- 配置路由出口 -->
<router-outlet></router-outlet>

2. Configure the router in App’s app-routing

  • The simplest component routing A path (routing Url) attribute and a component (Url corresponding to the loaded component) attribute are necessary: ​​

const routes: Routes = [
  {
    path: &#39;login&#39;,
    component: LoginComponent,
  },
  {
    path: &#39;home&#39;,
    component: HomeComponent,
  },
  {
    path: &#39;mine&#39;,
    component: MineComponent,
  },
];
  • When we accidentally access a non-existent How to configure our 404 page when using URL?

path supports a special wildcard to support "**". When there is no successful match in the routing table, it will finally point to the component corresponding to the wildcard

const routes: Routes = [
  ...
  {
    path: &#39;**&#39;,
    component: NotFountComponent,
  },
];

Note: The router matching policy is first come first served, so unspecific routing configurations are configured later.

3. Set a valid default route

Since our project has no specific route matching after default startup, which is not friendly, we need to set a valid default route route to display to the user.

  • The configured default route should be above the wildcard route.

const routes: Routes = [
  ...
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  ...
];

Configuring sub-modules & sub-routing

At this time our routing configuration is allapp-routing , this is of course feasible for simple applications, but with the iteration of applications and the increase of modules, it is obvious that configuring them together is a challenge for management and expansion, and the split of modules becomes inevitable.

1. Add a module configuration with routing for the Home component

Create a module configuration with routing for the Home component through cli: ng generate module pages/home/home --module app --flat --routing

imports: [
    BrowserModule,
    HomeRoutingModule,
    AppRoutingModule,
]

Note: Modules created with cli will be automatically configured to the root module, but we can adjust it manually Move the AppRoutingModule to the end in the following order to satisfy the first-come, first-served policy.

2. Transfer the routing configuration of the Home component to home-routing

const routes: Routes = [{
  path: &#39;home&#39;,
  component: HomeComponent,
}];

Note: After configuration, you can put the app The Home component configuration in -routing has been removed.

3. Supplement the subcomponents of the Home group module and configure the subroutes

  • Execute the command to create the subcomponents

    • ##ng g c pages/home/children/user-list

    • ng g c pages/home/children/user-detail

    • ng g c pages/home/children/edit-user

  • Add

    to the Home router configuration childrenproperty to configure sub-component routing

  • const routes: Routes = [{
      ...
      children: [
        {
          path: &#39;list&#39;,
          component: UserListComponent,
        },
        {
          path: &#39;detail&#39;,
          component: UserDetailComponent,
        },
        {
          path: &#39;edit&#39;,
          component: EditUserComponent,
        },
        {
          path: &#39;&#39;,
          redirectTo: &#39;/home/list&#39;,
          pathMatch: &#39;full&#39;
        }
      ]
    }];
  • Configure the sub-module routing exit the same as the root component

  • <div>
      <a [routerLink]="[&#39;/home/list&#39;]">列表</a>|
      <a [routerLink]="[&#39;/home/edit&#39;]">编辑</a>|
      <a [routerLink]="[&#39;/home/detail&#39;]">详情</a>
    </div>
    <!-- 配置路由出口 -->
    <router-outlet></router-outlet>

Route parameters

#1. Configure the parameter tokens that need to be carried when defining the route

  • Format: In the route After the configured path, add a token placeholder in the format

    /:key

  • {
      path: &#39;detail/:id&#39;,
      component: UserDetailComponent
    }
Note: This method inserts the token into the routing path to take place. In the method, id is a parameter that must be carried.

  • Carry parameters through

    routerLink

<a></a>
  • You need to use ActivatedRoute to get routing parameters in Angular :

Before using

ActivatedRoute, you must inject it into the target component

  • 方式1: 获取参数(路由参数变化可以被监听,适用于同一组件实例多次复用的情况)

this.route.paramMap.subscribe(
  (params: ParamMap) => {
    console.log(&#39;id :>> &#39;, params.get(&#39;id&#39;));
  }
)
  • 方式2: 获取参数(只获取到初始值)

const id = this.route.snapshot.paramMap.get(&#39;id&#39;)!;

ParamMap API:

成员 说明
has(name) 如果参数名位于参数列表中,就返回 true
get(name) 如果这个 map 中有参数名对应的参数值(字符串),就返回它,否则返回 null。如果参数值实际上是一个数组,就返回它的第一个元素。
getAll(name) 如果这个 map 中有参数名对应的值,就返回一个字符串数组,否则返回空数组。当一个参数名可能对应多个值的时候,请使用 getAll
keys 返回这个 map 中的所有参数名组成的字符串数组。

2. 通过Router的navigate跳转页面

当前组件注入Router对象

  • 无参数携带跳转:

this.router.navigate([&#39;/home/list&#39;]);
  • 携带参数跳转:

this.router.navigate([&#39;/home/list&#39;, { id: this.userId, name: this.userName }]);

注:矩阵URL标记法:;id=101;name=bom

懒加载

懒加载的目的是将模块的挂载延迟到我们使用的时候,避免首次打开页面就进行整体加载导致页面长时间不可用。

1. 配置无组件路由(空路由)

对路由进行分组而不增加额外的路径片段

{
    path: &#39;home&#39;,
    loadChildren: () =>
      import(&#39;./pages/home/home.module&#39;).then((m) => m.HomeModule),
}

2. 移除根模块中关于Home模块的导入,使得模块完整分离

微调home-routing中home组件的path配置为""

const routes: Routes = [{
  path: &#39;&#39;,
  component: HomeComponent,
  children: [
    ...
  ]
}];

3. 与懒加载相对的预加载

angular中配置懒加载后模块的加载被延迟到来使用时,但是有一些组件是需要优先加载并在使用的时候可以及时运行。

angular中的Router模块提供来两种预加载的策略:

  • 完全不预加载,这是默认值。惰性加载的特性区仍然会按需加载。

  • 预加载所有惰性加载的特性区。

  • 修改方式:RouterModule.forRoot()的参数二的对象支持设置加载模式的属性preloadingStrategy

    • PreloadAllModules: 预加载有所模块

    • NoPreloading: 默认,不进行预加载

  • 这么鸡肋的属性必须要支持自定义,我们来看一下:

    • 在需要预加载的路由配置对象中添加data对象并增加preload属性,值设置为true表示开启预加载。

    • 通过cli来生成一个服务用来完成我们的预加载策略:ng generate service selective-preloading-strategy

    • 将我们创建的服务实现接口PreloadingStrategy

    • 自定义的策略和默认支持的两种策略使用方法一致。

import { Injectable } from &#39;@angular/core&#39;;
import { PreloadingStrategy, Route } from &#39;@angular/router&#39;;
import { Observable, of } from &#39;rxjs&#39;;

@Injectable({
  providedIn: &#39;root&#39;,
})
export class SelectivePreloadingStrategyService implements PreloadingStrategy {
  preloadedModules: string[] = [];

  preload(route: Route, fn: () => Observable<any>): Observable<any> {
    // 通过检查路由配置来决定是否做预加载
    if (route.data && route.data.preload && route.path != null) {
      // 参数1: 要加载的路由
      this.preloadedModules.push(route.path);
      // 参数2: 加载器
      return fn();
    } else {
      return of(null);
    }
  }
}

结语

以上就是最近对Angular路由的学习整理,对于路由还有一块守卫没有提到,我们抽时间再来整理一下。

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of A brief discussion on how to use routing in Angular?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete