【发布时间】:2019-08-30 11:38:30
【问题描述】:
我正在编写一个名为 libModule 的 Angular 库,我需要在模块导入的 .forRoot() 中传入一个配置对象。
我正在尝试使用 InjectionToken 执行此操作,但是当我使用 ng build--prod 运行我的应用程序(使用 ng-packagr 安装 libModule 构建)时,我得到了一个像这样的错误
“TestModule”模板编译期间出现错误 装饰器不支持函数调用,但调用了“libModule”。
libModule
import { NgModule } from '@angular/core';
import { CONFIG, Config } from './config';
import { LibService } from './libService';
@NgModule({ ... })
export class LibModule {
static forRoot(config?: any): ModuleWithProviders {
return {
ngModule: LibModule,
providers: [
LibService,
{ provide: CONFIG, useValue: config }
]
};
}
}
config.ts
import { InjectionToken } from '@angular/core';
export const CONFIG = new InjectionToken<Config>('config');
export interface Config {
key?: string;
}
libService.ts
import { Observable } from "rxjs/Observable";
import { Injectable, Inject } from "@angular/core";
import { Config, LIB_CONFIG } from "./config";
@Injectable()
export class LibService {
private key: string;
constructor(
@Inject(LIB_CONFIG) config: any
) {
this.key = config.KEY;
console.log('ewrwerwerwrewrewr'+this.key);
}
}
消费应用TestModule
import { NgModule } from '@angular/core';
import { LibModule } from 'some-library';
@NgModule({
imports: [
libModule.forRoot({
// <-- config values here
})
]
})
【问题讨论】:
-
这可能会有所帮助:stackoverflow.com/a/43293449/3055401
-
不,只有当我使用 --prod 运行我的消费项目时。错误发生了
标签: angular