首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Angular Ivy:读取模块提供程序

Angular Ivy 是 Angular 的一个编译器,它在 Angular 9 中引入,用于替代之前版本中的 View Engine

  1. 创建一个简单的模块 首先,创建一个简单的模块作为示例。例如,新建一个文件 my-module.module.ts: import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MyComponent } from './my-component.component'; @NgModule({ declarations: [MyComponent], imports: [CommonModule], exports: [MyComponent], }) export class MyModule {}
  2. 创建一个使用 @NgModule 装饰器的类 接下来,创建一个使用 @NgModule 装饰器的类。这个类将作为模块提供者。新建一个文件 module-provider.ts: import { MyModule } from './my-module.module'; export function ModuleProvider() { return { ngModule: MyModule, }; }
  3. 导入模块提供者 现在,您需要在您的主模块(通常是 app.module.ts)中导入 ModuleProvider 并提供它: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { MyComponent } from './my-component.component'; import { ModuleProvider } from './module-provider'; @NgModule({ declarations: [AppComponent, MyComponent], imports: [BrowserModule], providers: [ { provide: 'MyModule', useFactory: ModuleProvider, }, ], bootstrap: [AppComponent], }) export class AppModule {}
  4. 使用模块 最后,在需要使用 MyModule 的组件中,通过依赖注入(DI)来获取它:
代码语言:javascript
复制
import { Component, Inject } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<my-component></my-component>`,
})
export class AppComponent {
  constructor(@Inject('MyModule') private myModule: MyModule) {
    console.log(myModule);
  }
}
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券