Angular Workspace/Monorepo,forRoot 给我错误。“‘forRoot’的值无法静态确定,因为它是外部声明。”

har*_*ish 6 angular angular-library angular-workspace-configuration

我有一个名为 Themex 的库。

//envInjector.ts
    import {InjectionToken} from "@angular/core";
    export const ENVIRONMENT = new InjectionToken<{[key: string]: any}>('ENVIRONMENT');
Run Code Online (Sandbox Code Playgroud)

//themex.module.ts

import {ENVIRONMENT} from "./envInjector";
 
    
    @NgModule({
      declarations: [
    ThemexComponent,
    ModalComponent,
    UploadComponent,
    AlertComponent,

  ],
  imports: [
    CommonModule
  ],
  exports: [
    ThemexComponent,
    ModalComponent,
    UploadComponent,
    AlertComponent,
  ],
  providers: []
})

export class ThemexModule {
  static forRoot(config: {[key: string]: any}): ModuleWithProviders<any> {
    return {
      ngModule: ThemexModule,
      providers: [
        {
          provide: ENVIRONMENT,
          useValue: config
        }
      ]
    };
  }

}
Run Code Online (Sandbox Code Playgroud)

该库被导入到同一角度工作空间内的角度项目中。

import {ThemexModule} from "themex";
Run Code Online (Sandbox Code Playgroud)

如果我按照上面给出的方式导入它,我会收到错误。

“‘forRoot’的值无法静态确定,因为它是外部声明。”

但是,如果我按照下面给出的方式导入它,一切似乎都有效。

import {ThemexModule} from "../../../themex/src/lib/themex.module";
Run Code Online (Sandbox Code Playgroud)

我在用着

Angular CLI: 12.0.5
Node: 14.16.1
Run Code Online (Sandbox Code Playgroud)

我的编译器选项。tsConfig.json 在此输入图像描述

所有错误都是在我执行ng serve. 我没有尝试过构建。

Car*_*ick 11

这几天我遇到了这个问题,我想我已经找到了解决方案。对我来说,当我从 Angular 10 升级一些库的依赖项时,就发生了这种情况。

我们的解决方案是确保 ModuleWithProviders 返回类型是模块的强类型,因此在您的情况下:

export class ThemexModule {
  static forRoot(config: {[key: string]: any}): ModuleWithProviders<ThemexModule> {
    [...]
}
Run Code Online (Sandbox Code Playgroud)