首页 > 解决方案 > 具有默认值的依赖项的 Angular 服务 - 构建错误未知标识符 []

问题描述

我创建了这样的服务:

@Injectable({ providedIn: 'root' })
export class TestService {
  value: any;
  constructor(value: string = 'a') {
    this.value = value;
  }
}

它无法构建ng build -aot

ERROR in : Error: Internal error: unknown identifier []
    at Object.importExpr$$1 [as importExpr] (C:\MyProject\node_modules\@angular\compiler\bundles\compiler.umd.js:24170:27)
    at C:\MyProject\node_modules\@angular\compiler\bundles\compiler.umd.js:18100:37
    at Array.map (<anonymous>)
    at InjectableCompiler.depsArray (C:\MyProject\node_modules\@angular\compiler\bundles\compiler.umd.js:18066:25)
    at InjectableCompiler.factoryFor (C:\MyProject\node_modules\@angular\compiler\bundles\compiler.umd.js:18130:36)
    at InjectableCompiler.injectableDef (C:\MyProject\node_modules\@angular\compiler\bundles\compiler.umd.js:18149:44)
    at InjectableCompiler.compile (C:\MyProject\node_modules\@angular\compiler\bundles\compiler.umd.js:18159:106)
    at C:\MyProject\node_modules\@angular\compiler\bundles\compiler.umd.js:24015:90
    at Array.forEach (<anonymous>)
    at AotCompiler._emitPartialModule2 (C:\MyProject\node_modules\@angular\compiler\bundles\compiler.umd.js:24015:25)
    at C:\MyProject\node_modules\@angular\compiler\bundles\compiler.umd.js:24008:48
    at Array.reduce (<anonymous>)
    at AotCompiler.emitAllPartialModules2 (C:\MyProject\node_modules\@angular\compiler\bundles\compiler.umd.js:24007:26)
    at AngularCompilerProgram._emitRender2 (C:\MyProject\node_modules\@angular\compiler-cli\src\transformers\program.js:300:31)
    at AngularCompilerProgram.emit (C:\MyProject\node_modules\@angular\compiler-cli\src\transformers\program.js:201:22)
    at AngularCompilerPlugin._emit (C:\MyProject\node_modules\@ngtools\webpack\src\angular_compiler_plugin.js:879:49)

并在此之前发出警告:

警告:无法解析 C:/MyProject/src/app/shared/context/test.service.ts: (?) 中 TestService 的所有参数。这将成为 Angular v6.x 中的错误

关于这个警告的一个奇怪的事情是,事实上我正在使用Angular 7.2,而错误警告我这将是 Angular 6 中的一个问题......


我找到了解决方法,将服务更改为使用工厂函数:

@Injectable({ providedIn: 'root', useFactory: () => new TestService('a') })
export class TestService {
  value: any;
  constructor(value: string) {
    this.value = value;
  }
}

现在它构建成功,但警告消息仍然存在。而且我不确定这是解决它的正确方法。

我应该如何创建具有依赖关系的服务并为其提供默认值?

标签: angulartypescriptdependency-injectionangular-cli

解决方案


服务不应包含任何参数。如果您选择以这种方式构建它,您将无法在 DI 场景中使用它,这会给您带来问题。我的建议是使用公共方法 setValue()。并创建具有默认值的变量。


推荐阅读