要将参数传递给NgModule,可以使用Angular提供的forRoot
方法。下面是一个示例:
首先,创建一个名为MyModule
的NgModule,并定义一个带有参数的静态方法forRoot
,该方法接受参数并返回一个ModuleWithProviders
对象。在该方法内部,我们可以将参数存储在一个静态变量中,以便在整个应用程序中访问。
import { NgModule, ModuleWithProviders } from '@angular/core';
@NgModule({
// 模块的其他配置
})
export class MyModule {
static forRoot(config: any): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [
{ provide: 'config', useValue: config }
]
};
}
}
然后,在应用程序的根模块中使用forRoot
方法传递参数:
import { NgModule } from '@angular/core';
import { MyModule } from './my.module';
const config = {
// 参数配置
};
@NgModule({
imports: [
MyModule.forRoot(config)
],
// 根模块的其他配置
})
export class AppModule { }
现在,可以在应用程序的其他组件或服务中注入config
参数:
import { Component } from '@angular/core';
import { Inject } from '@angular/core';
@Component({
selector: 'my-component',
template: 'Config value: {{ config }}'
})
export class MyComponent {
constructor(@Inject('config') private config: any) { }
}
这样,我们就可以将参数传递给NgModule并在整个应用程序中使用它。