Angular 12外部库中的依赖注入



我需要将一个服务注入到一个外部库中,以便在指令中使用它。这个指令将在不同的应用中使用,在每个应用的不同模块中使用。每个模块将注入自己的服务。

我在库的模块中创建了一个注入令牌和一个服务接口,并将其导入到将要在主应用中使用的模块中。

然后我使用useExisting和这个令牌提供服务,并在指令中在构造函数中使用@Inject(INJECTION_TOKEN)。

,但我总是有这样的结果,当我加载组件,其中使用的指令:NullInjectorError: R3InjectorError(DashboardModule)[InjectionToken服务令牌->InjectionToken服务令牌

In my library module

import { Directive } from './directives/directive.directive';
@NgModule({
exports: [
...,
Directive
],
imports: [CommonModule,...],
declarations: [
...,
Directive
]
})
export class LibraryModule {
}
export const SERVICE_ADAPTER: InjectionToken<ServiceAdapter> =
new InjectionToken('service token');
export interface ServiceAdapter {
a(): void
}

In my library指令:

import { Directive, ElementRef, EventEmitter, HostListener, Inject, Input, Output } from '@angular/core';
import { ServiceAdapter, SERVICE_ADAPTER } from '../library.module';
@Directive({
selector: '[myDirective]'
})
export class Directive {
@Input() field: string = ''
@Input() method: string = ''

constructor(private el: ElementRef, @Inject(SERVICE_ADAPTER) protected service: ServiceAdapter) {}
@HostListener('keyup', ['$event'])
keyup(event: any) {
...
}

}

在我将要使用它的模块中:

...
import { LibraryModule,SERVICE_ADAPTER } from 'Library...';
@NgModule({providers: [
{ provide: SERVICE_ADAPTER, useExisting: ProjectsService }
],
declarations: [
...
],
imports: [
LibraryModule,
]
})
export class ProjectsModule {
}

如果我理解对了,上面的链接就是你的解决方案。如果你想为每个惰性加载模块定制/单独的service_adapter "forRoot - Concept"是你的解决方案。

你需要在库中为你的指令创建一个模块,如:

export interface IDirectiveModuleConfig {
serviceAdapterConfiguration?: Provider;
}

@NgModule()
export class YourDirectiveModule{
public static forRoot(config: IDirectiveModuleConfig = {}): ModuleWithProviders<YourDirectiveModule> {
return {
ngModule: YourDirectiveModule,
providers: [
config.serviceAdapterConfiguration
]
};
}
}

在你的惰性加载模块中,你可以指定如何提供你的服务


@NgModule(
{
imports: [
YourDirectiveModule.forRoot({
provide: ServiceAdapter,
useClass: CustomImplementationServiceAdapter
})
]
}
)
export class LazyLoadedModule {
}

最新更新