Angular7+ 路由

843 阅读2分钟

1、RouterModule.forRoot() 和 RouterModule.forChild()

RouterModule对象为提供了两个静态的方法:forRoot()和forChild()来配置路由信息。

RouterModule.forRoot()方法用于在主模块中定义主要的路由信息. RouterModule.forChild()与 Router.forRoot()方法类似,但它只能应用在特性模块(子模块)中。

即根模块中使用forRoot(),子模块中使用forChild()。

2、懒加载:loadChildren

这里使用到了懒加载LoadChildren属性。这里没有将对应的模块导入到AppModule中,而是通过loadChildren属性,告诉Angular路由依据loadChildren属性配置的路径去加载对应的模块。这就是模块懒加载功能的具体应用,当用户访问 /xxx/** 路径的时候,才会加载对应的模块,这减少了应用启动时加载资源的大小。

懒加载的实现

1、创建项目

ng new angularLaod --routing (生成默认带有routing module 的项目)

执行 --routing会执行以下步骤

  • 创建app-routing.module.ts
  • 将app-routing.module.ts导入到app.module.ts
  • 在app.component.html添加

2、生成子模块

ng g m childrenLaod --routing

生成带module.ts,routing.ts 的文件

3、在app-routing.module模块中导入children-load模块

const routes: Routes = [
  {path:'',redirectTo:'child'},
  {path:'child',loadChildren:'./children-load/children-load.module#ChildrenLoadModule'}
];

懒加载的文件要注意:

// app.module.ts中:
declarations: [
   AppComponent,
   DashboardComponent,
   HeroDetailComponent,
   HeroesComponent,
   TestComponent,
 ],

这里面的文件,采用懒加载的模块是引用不到得,因为lazy加载文件有自己的ngModule ,如果要使用的组件是同一个,最好建立一个shareModule模块;

采用commonModule 将共享文件放进去,之后的Module里使用再加载进imports中;

Tips1

如何解决第二次刷新出现404问题:

[RouterModule.forRoot(routes,{useHash:true})]

Tips2

navigate() 该方法支持的参数类型和routerLink指令一样,所以他们的作用也是一样的:

this.router.navigate(['test', id]);

或者:

this.router.navigate(['test']);

调用该方法后页面会自动跳转到对应的路由地址;

this.router.navigate(['test'], { relativeTo: this.route});

我们可以设置一个参照路径,参照路径this.route从ActivatedRoute里面取;

配置这个可以让自己知道相对于什么位置导航,this.route就是相对于当前的路由进行导航,

假如当前url:localhost:4200/hero ,那么导航后的结果就是:localhost:4200/hero/test

Tip3

navigateByUrl() : 这个叫做绝对路由

this.router.navigateByUrl('home');

可以帮助你快速的切换到某个路由下面,如果你当时的路由是这样的:

// localhost:4200/hero/test 点击这个路由后就是:
// localhost:4200/home 我们一般用这个路由来回到首页;
// 和navigate()的区别还有点是:这个不是根据参数来确定路由地址的

Tip4

router.config 会将页面所有的路由配置信息都显示:

url 输出当前 的路由path