我为我的项目创建了一个核心库,其中包含一些组件和服务。我用ng-packagr构建了这个库。在引用该库的消费项目中,我构建了我的webapp,其中包含该库提供的组件。到目前为止没什么特别的。但有时我希望一个组件(来自我的库)从库之外的服务调用一个方法。这个是可能的吗?我可以以某种方式将服务注入到在库中定义的组件中吗?
干杯
发布于 2018-04-22 06:14:17
我以前用这样的东西做到了这一点:
您的库的服务应该被定义为一个接口,而不是一个具体的实现(就像在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 {
}这是在记忆中,因为我目前没有代码,所以如果由于任何原因它不能工作,请让我知道。
https://stackoverflow.com/questions/49959537
复制相似问题