【问题标题】:InjectionToken for config not working with AoT用于配置的 InjectionToken 不适用于 AoT
【发布时间】:2018-06-15 13:54:55
【问题描述】:

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

我正在尝试使用 InjectionToken 执行此操作(显然是正确的方法),但出现 AoT 编译错误。

使用 AoT 编译时出错:

错误 TS4050:从导出的类返回公共静态方法的类型 有或正在使用来自外部模块的名称“InjectionToken” “/path/to/node_modules/@angular/core/src/di/injection_token” 但不能命名。

感谢任何帮助。

module.ts:

import { NgModule } from '@angular/core';
import { CONFIG, Config } from './config';

@NgModule({ ... })
export class SomeModule {
    static forRoot(config?: Config) {
        return {
            ngModule: SomeModule,
            providers: [
                { provide: CONFIG, useValue: config }
            ]
        };
    }
}

config.ts:

import { InjectionToken } from '@angular/core';

export const CONFIG = new InjectionToken<Config>('config');

export interface Config {
    some?: string;
    values?: string;
    here?: string;
}

其他应用程序的预期用途:

import { NgModule } from '@angular/core';
import { SomeModule } from 'some-library';

@NgModule({
    imports: [
        SomeModule.forRoot({
            // <-- config values here
        })
    ]
})

(Angular 5,TypeScript 2.6.2)

【问题讨论】:

  • 这个答案可能有用 - stackoverflow.com/a/43293449/3055401
  • 谢谢,但是通过摆脱 InjectionToken 可以避免这个问题。根据我的阅读,最佳做法是在字符串上使用InjectionToken
  • 我的猜测是您必须(并且无论如何应该)指定 forRoot 方法返回的类型:: ModuleWithProviders
  • 0_0 就是这样,JB。谢谢!

标签: angular typescript


【解决方案1】:

JB Nizet 在上面的 cmets 中回答...

需要指定forRoot方法返回的类型,ModuleWithProviders

import { NgModule } from '@angular/core';
import { CONFIG, Config } from './config';

@NgModule({ ... })
export class SomeModule {
    static forRoot(config?: Config): ModuleWithProviders {
        return {
            ngModule: SomeModule,
            providers: [
                { provide: CONFIG, useValue: config }
            ]
        };
    }
}

【讨论】:

    猜你喜欢
    • 2018-08-06
    • 2017-07-04
    • 2017-12-09
    • 2020-11-18
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    相关资源
    最近更新 更多