我为我的项目创建了一个包含一些组件和服务的核心库。我用ng-packagr构建了库。在引用库的消费项目中,我构建了包含库提供的组件的webapp。到目前为止没什么特别的。但有时我想要一个组件(来自我的lib)从lib外部的服务调用一个方法。这可能吗?我可以以某种方式将服务注入到库中定义的组件吗?
干杯
答案 0 :(得分:7)
我以前用这样的东西实现了这个目标:
您的图书馆服务应该被定义为一个接口,而不是一个具体的实现(就像在OO语言中经常做的那样)。如果您的实现应用程序有时只想传递自己的服务版本,那么您应该在库中创建一个默认服务,并将其用作:
import { Component, NgModule, ModuleWithProviders, Type, InjectionToken, Inject, Injectable } from '@angular/core';
export interface ILibService {
aFunction(): string;
}
export const LIB_SERVICE = new InjectionToken<ILibService>('LIB_SERVICE');
export interface MyLibConfig {
myService: Type<ILibService>;
}
@Injectable()
export class DefaultLibService implements ILibService {
aFunction() {
return 'default';
}
}
@Component({
// whatever
})
export class MyLibComponent {
constructor(@Inject(LIB_SERVICE) libService: ILibService) {
console.log(libService.aFunction());
}
}
@NgModule({
declarations: [MyLibComponent],
exports: [MyLibComponent]
})
export class LibModule {
static forRoot(config?: MyLibConfig): ModuleWithProviders {
return {
ngModule: LibModule,
providers: [
{ provide: LIB_SERVICE, useClass: config && config.myService || DefaultLibService }
]
};
}
}
然后在您的实现应用程序中,您可以通过库的forRoot
方法传递可选配置(请注意forRoot
应该只针对每个应用程序调用一次,并且可以在最高级别调用。请注意,我已将config
参数标记为可选,因此即使您没有要传递的配置,也应调用forRoot
。
import { NgModule, Injectable } from '@angular/core';
import { LibModule, ILibService } from 'my-lib';
@Injectable()
export class OverridingService implements ILibService {
aFunction() {
return 'overridden!';
}
}
@NgModule({
imports: [LibModule.forRoot({ myService: OverridingService })]
})
export class ImplementingModule {
}
这是来自记忆,因为我现在没有代码可以提交,所以如果它因任何原因无效,请告诉我。