如何使forRoot方法的参数可选?

时间:2018-04-20 06:10:10

标签: angular typescript

我通过forRoot在我的lib中提供了我的服务所需的配置。 我希望这个库与默认配置一起使用,如果消费app不想要的话。我尝试使用@Optional,但无效。

这是我的示例模块

@NgModule({
    imports: [CommonModule, HttpClientModule, FormsModule, ReactiveFormsModule, RouterModule],
    declarations: [MyComponent],
    exports: [MyComponent]
})
export class MyModule {
  // Configure url, clientid & other for widget specific configuration
  public static forRoot(@Optional() options: Config): ModuleWithProviders {
    if (!options) {
      options = { url: 'default-url', otherparams: []};
    }
    return { ngModule: MyModule, providers: [MyService, {provide: Config, useValue: options} ]};
  }

当我在使用应用

时使用此代码时,此代码无效
MyModule.forRoot()

它给了我错误:

  

参数0而不是1。

甚至可以选择params吗?如果是,怎么样?

有没有更好的方法来接受使用app的配置(组件的输入除外)?

1 个答案:

答案 0 :(得分:2)

@Optional仅在DI机制想要注入服务时使用。您只能在构造函数中使用它。如果您的参数必须是可选参数,则可以使用?可选参数。

public static forRoot(options?: Config): ModuleWithProviders {

    if (!options) {
       options = { url: 'default-url', otherparams: []};
    }

    return { ngModule: MyModule, providers: [MyService, {provide: Config, useValue: options} ]};

}

你可以称之为MyModule.forRoot() - 没有参数。