Angular应用内路由(In App Route)的最佳实践

时间:2022-07-23
本文章向大家介绍Angular应用内路由(In App Route)的最佳实践,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Angular官网里关于路由开发的最佳实践指导:

In Angular, the best practice is to load and configure the router in a separate, top-level module that is dedicated to routing and imported by the root AppModule.

By convention, the module class name is AppRoutingModule and it belongs in the app-routing.module.ts in the src/app folder.

使用命令行生成路由module:

ng generate module app-routing --flat --module=app

flat的含义: 把生成的module放到项目根目录下面,而不是放到一个单独目录下。

–module=app:告诉CLI该module生成完毕后,注册到AppModule的imports数组内。

代码如下:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HeroesComponent } from './heroes/heroes.component';

const routes: Routes = [
  { path: 'heroes', component: HeroesComponent }
];

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

Routes告诉Router,当用户点击了url或者将路径粘贴到地址栏之后,应该打开哪个视图。

RouterModule.forRoot(routes)方法的作用:

configure the router at the application’s root level. The forRoot() method supplies the service providers and directives needed for routing, and performs the initial navigation based on the current browser URL.

使用route之前的app Component html:

使用route之后:

<h1>{{title}}</h1>
<router-outlet></router-outlet>
<app-messages></app-messages>

The tells the router where to display routed views: 告诉router在哪里显示被路由器控制的视图。

RouterOutle是router指令,整个AppComponent范围内都可用,因为在AppModule里导入了AppRoutingModule,而后者又export了RouterModule.

测试: