【问题标题】:Adding Library configs using `forRoot()` and `InjectionToken` with angular5使用 `forRoot()` 和 `InjectionToken` 和 angular5 添加库配置
【发布时间】: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
        })
    ]
})

【问题讨论】:

标签: angular


【解决方案1】:

就我而言,我删除了returnforRoot 函数之前的调试语句。

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

【讨论】:

  • 非常感谢。您的回答解决了我的问题。
猜你喜欢
  • 2017-09-03
  • 2018-09-21
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 2018-06-15
  • 1970-01-01
相关资源
最近更新 更多