【问题标题】:Angular 6 library root Provider with factory带有工厂的 Angular 6 库根提供程序
【发布时间】:2018-09-10 21:42:45
【问题描述】:

我正在尝试使用需要来自最终用户应用程序的配置的服务构建一个库。

但是当我构建库时,我收到了这个警告:

警告:Can't resolve all parameters for CacheService in ... 这将成为 Angular v6.x 中的错误

代码如下:

@Injectable()
export class CacheService {
  private config: Config;

  constructor(config: Config) {
    this.config = config;
  }
}

@NgModule({

})
export class MyModule {
  static forRoot(config: Config): ModuleWithProviders {
    return {
      ngModule: MyModuleRoot,
      providers: [
        { provide: CacheService, useFactory: cacheServiceFactory, deps: [config] }
      ]
    };
  }
}

export function cacheServiceFactory(config: Config): CacheService {
  return new CacheService(config);
}

当我尝试在构造函数中注入 CacheService 来运行我的主应用程序时,我得到了 AppComponent_Host.ngfactory.js? [sm]:1 ERROR 错误:StaticInjectorError(AppModule)[CacheService -> [object Object]]:

但我不希望它被注入,而是使用我创建的工厂......

我的代码有什么问题?

【问题讨论】:

    标签: angular angular6


    【解决方案1】:

    好的,这就是解决方案,

    您需要提供配置,以便将其注入服务中。 这样就不需要工厂了!

    @NgModule({
    
    })
    export class MyModule {
    
      static forRoot(config: Config): ModuleWithProviders {
        return {
          ngModule: MyModuleRoot,
          providers: [
            { provide: Config, useValue: config },
            CacheService
          ]
        };
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 2020-05-15
      • 2018-12-27
      • 2015-12-04
      • 1970-01-01
      相关资源
      最近更新 更多