使用 angular5 的 'forRoot()' 和 'InjectionToken' 添加库配置



我正在编写一个名为libModule的Angular库,我需要在模块导入的.forRoot((中传入一个配置对象。

我正在尝试使用 InjectionToken 执行此操作,但是当我使用 ng build--prod 运行我的应用程序(使用 ng-packagr 安装的 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 }
            ]
        };
    }
}

配置.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);
  }
}

使用应用程序测试模块

import { NgModule } from '@angular/core';
import { LibModule } from 'some-library';
@NgModule({
    imports: [
        libModule.forRoot({
            // <-- config values here
        })
    ]
})

就我而言,我在return函数之前删除了调试语句forRoot

参考: https://github.com/angular/angular-cli/issues/9358#issuecomment-435288467

最新更新