简体   繁体   English

Angular 12 外部库中的依赖注入

[英]Angular 12 Dependency injection in external library

I need to inject a service into an external library for use it in a directive.我需要将服务注入外部库以便在指令中使用它。 this directive will be used in diferents apps and in diferents modules in each app.该指令将在不同的应用程序和每个应用程序的不同模块中使用。 Each module will inject its own service.每个模块都会注入自己的服务。

Im creating an inyection token and a service interface in the module of the library, and importing its in the modules where are going to be used in the pricipal app.我在库的模块中创建了一个 inyection 令牌和一个服务接口,并将其导入到将在主要应用程序中使用的模块中。

then I provide the service using useExisting with this token, and in the directive use @Inject(INJECTION_TOKEN) in the constructor.然后我使用带有此令牌的 useExisting 提供服务,并在指令中在构造函数中使用 @Inject(INJECTION_TOKEN)。

but i allways have this result when i load the componen where is used directive: "NullInjectorError: R3InjectorError(DashboardModule)[InjectionToken service token -> InjectionToken service token"但是当我加载使用指令的组件时,我总是得到这个结果:“NullInjectorError: R3InjectorError(DashboardModule)[InjectionToken service token -> InjectionToken service token”

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 Directive:在我的图书馆指令中:

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) {

        ...

  }


}

In the module where im going tu use it:在我要使用它的模块中:

...
import { LibraryModule,SERVICE_ADAPTER } from 'Library...';

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

}

When I understand you right, the link above is the solution for you.当我理解正确时,上面的链接就是适合您的解决方案。 If you want for each lazy loaded module your custom / individual instance of service_adapter "forRoot - Concept" is your solution.如果你想要每个延迟加载的模块,你的自定义/单独的 service_adapter 实例“forRoot - Concept”就是你的解决方案。

You need a module for your directive in the library like:您需要在库中为您的指令提供一个模块,例如:

export interface IDirectiveModuleConfig {
    serviceAdapterConfiguration?: Provider;
}


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

In your lazy loaded module you can specify how your service will be provided在您的延迟加载模块中,您可以指定如何提供您的服务


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM