Angular 10延迟加载路由不起作用

时间:2020-10-28 13:17:24

标签: angular routes lazy-loading

我无法弄清楚为什么这种情况可行,而无法解决以下情况。

方案1: 这样可以为模块正确加载CasesModule组件。

NavigationEnd(id: 2, url: '/cases', urlAfterRedirects: '/cases/current')

app-routing.modules.ts:

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";

const routes: Routes = [
   {
    path: "cases",
     loadChildren: () => import("./cases/cases.module").then(m => m.CasesModule)
   },
  { path: "**", redirectTo: "", pathMatch: "full" }
];

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

cases.routing.modules:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { CurrentCasesComponent } from './current-cases/current-cases.component';

const routes: Routes = [
    { path: '', redirectTo: 'current', pathMatch: 'full' },
    {
      path: 'current',
      component: CurrentCasesComponent,
    },
];

@NgModule({
  declarations: [],
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class CasesRoutingModule {}

方案2:

我想动态加载模块路由,因为我正在使用SystemJs import动态导入模块。

主要区别在于: app-routing.modules.ts:

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";

const routes: Routes = [
  // {
  //   path: "cases",
  //   loadChildren: () => import("./cases/cases.module").then(m => m.CasesModule)
  // },
  { path: "**", redirectTo: "", pathMatch: "full" }
];

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

我想用组件或服务加载路由。

app.component.ts

import { Component, VERSION } from "@angular/core";
import { Route, Router } from "@angular/router";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent {
  constructor(private router: Router) {}

  route() {
    this.createRoute();
    // test navigation
    this.router.navigate(["cases"]);
  }

  createRoute() {
    const appRoutes = [...this.router.config];
    const route: Route = {
      path: "cases",
      loadChildren: () =>
        import("./cases/cases.module").then(m => m.CasesModule)
    };
    appRoutes.push(route);
    this.router.resetConfig(appRoutes);
  }
}

app.component.html

<button  (click)="route()">cases</button>
<app-shell></app-shell>

我可以看到路由已在路由器配置中正确加载,但是当我调用路由并重定向到默认页面时,它没有创建_LoadedConfig。

NavigationEnd {id: 2, url: "/cases", urlAfterRedirects: "/"}

以下是重现该问题的示例的链接: StackBlitz

我想念什么?

1 个答案:

答案 0 :(得分:0)

在createRoute()函数中,您将在appRoutes数组中推送新路由,而不是推送尝试unshift()

appRoutes.unshift(route);

实际上,问题是push在数组的末尾添加了元素,并且您必须在末尾使用通配符路由。

unshift将在数组的开头添加元素,希望这会有所帮助