2

I am wondering why Angular 2 providers syntax isn't working when I want to provide a specific value via the useValue field.

For instance, in the app.module.ts I have

// Abstracted base class (since interfaces don't work with libraries and tsc)
export class Base {
  constructor(public bar:Bar) {
  }
}

export class Foo extends Base {
  constructor(public bar:Bar) {
    super(bar);
  }
}

export class Bar {
  hello = "world";
}

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
  ],
  providers: [
    {provide: Base, useValue: new Foo(new Bar())}
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Attempting this throws an error during ng build:

ERROR in Error encountered resolving symbol values statically. Calling function 'Foo', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol AppModule in /Users/tbeauvais/Code/example-sdk/src/app/app.module.ts, resolving symbol AppModule in /Users/tbeauvais/Code/example-sdk/src/app/app.module.ts

I am getting around this by simply using the field, useClass, and then specifying the parameters through deps like this:

...
providers: [
  Bar,
  {provide: Base, useClass: Foo, deps:[Bar]}
],
...

It works, it's just not ideal and I am wondering what I am missing here. Also, I don't want to have to inject Bar for no reason.

Any help would be greatly appreciated. Cheers!

4

1 回答 1

4

我知道这个错误听起来很神秘,但归根结底并非如此。某些配置(通常是 aot-cli 配置)不允许无法静态分析的代码。为了做到这一点,必须导出一个函数,就像错误状态一样,像这样

创建一个看起来像这样的 ts 文件

export function UseClassFunction(){ return function() { return new Foo(new Bar());}} 然后导入它并在 useValue 上使用它

{provide: Base, useValue: UseClassFunction}

于 2017-05-19T15:51:59.747 回答