[英]Angular 6 library root Provider with factory
I'm trying to build a library with a Service that needs a config from the end-user application. 我正在尝试使用需要从最终用户应用程序进行配置的服务来构建库。
But when I build the library I get this warning: 但是,当我构建库时,会收到以下警告:
Warning: Can't resolve all parameters for CacheService in ... This will become an error in Angular v6.x 警告:在...中无法解析CacheService的所有参数。这将成为Angular v6.x中的错误
Here is the code: 这是代码:
@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);
}
When I try to run my main-app with CacheService injected in a constructor, I get AppComponent_Host.ngfactory.js? 当我尝试在构造函数中注入CacheService来运行我的主应用程序时,得到了AppComponent_Host.ngfactory.js吗? [sm]:1 ERROR Error: StaticInjectorError(AppModule)[CacheService -> [object Object]]:
[sm]:1错误错误:StaticInjectorError(AppModule)[CacheService-> [object Object]]:
but I don't want it to be injected but use the factory I've created... 但是我不想注入它,而是使用我创建的工厂...
What's wrong with my code ? 我的代码有什么问题?
Ok here is the solution, 好的,这是解决方案,
You need to provide the config so it can be injected in the service. 您需要提供配置,以便可以将其注入服务中。 That way, there is no need for a factory!
这样,就不需要工厂了!
@NgModule({
})
export class MyModule {
static forRoot(config: Config): ModuleWithProviders {
return {
ngModule: MyModuleRoot,
providers: [
{ provide: Config, useValue: config },
CacheService
]
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.