【问题标题】:Angular how to import RouterModule for lazy loading ComponentAngular如何导入RouterModule以延迟加载组件
【发布时间】:2022-07-28 16:07:17
【问题描述】:

我的 Angular 13 项目有一个延迟加载组件

  async loadModals() {
    this.viewContainerRef.clear();
    const { McComponent } = await import('./components/modal/mc.component');
    this.viewContainerRef.createComponent(this.componentFactoryResolver.resolveComponentFactory(McComponent));
  }

但不知道如何在其中导入 RouterModule 以获得工作链接

        <a [routerLink]="['/mcu']" class="upgrade-link">
          {{ upgradeLinkLable | translate }}
        </a>

【问题讨论】:

  • 你能提供一个stackblitz的例子吗,这样我可以更容易地提供帮助

标签: angular


【解决方案1】:

好的,我知道了。

在大多数延迟加载组件的示例中,都会在组件文件中添加这个 NgModule 装饰器。

例如

@NgModule({
  declarations: [GreetComponent],
  imports: [FormsModule]
})
class PlanetComponentModule {}

我没有找到更具体的信息,我有点困惑。 所以这里是关键。

这是我的模态组件示例,但我先提一下重点。

  1. 你在文件底部添加@NgModule!

  2. 您添加所有您想在 NgModule 中的 imports 部分。对于 declarations 部分,您应该添加主要组件和它使用的所有其他组件(在我的情况下为 MoveFilesComponent)。这样一来,RouterModule 将可供所有人使用。

  3. 模块的名称与组件无关,因此您可以随意命名,但无论如何要更具体

  4. 如果您需要一些服务,而不是任何模块的一部分,或者只需要该服务,您可以将其添加到 @Component providers 插槽中(我为 MoveFilesService 做过)。

希望对您有所帮助。干杯!

import { Component, NgModule, OnDestroy, OnInit } from '@angular/core';
import { RouterModule } from '@angular/router';
import { MoveFilesService } from './services/move-files.service';
import { MoveFilesComponent } from './modals/move-files/move-files.component';



@Component({
  selector: 'nx-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss'],
  providers: [MoveFilesService],
})
export class ModalComponent implements OnInit, OnDestroy {
 ...
}

@NgModule({
  declarations: [
    ModalComponent,
    MoveFilesComponent,
  ],
  imports: [RouterModule],
})
class ModalModule {} /* Whatever you name it */

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2023-03-13
    相关资源
    最近更新 更多