代码之家  ›  专栏  ›  技术社区  ›  user970470

角度5维修更换/超越

  •  11
  • user970470  · 技术社区  · 8 年前

    我为我的项目创建了一个核心库,其中包含一些组件和服务。我用ng Packager构建了库。在引用库的消费项目中,我构建了包含库提供的组件的webapp。目前没有什么特别的。但有时我需要一个组件(来自我的lib)从lib之外的服务调用一个方法。这可能吗?我能否以某种方式将服务注入到库中定义的组件中?

    干杯

    1 回复  |  直到 8 年前
        1
  •  22
  •   UncleDave    8 年前

    我以前用过这样的方法:

    您的库服务应该定义为一个接口,而不是一个具体的实现(在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 方法(请注意 福鲁特 每个应用程序只能调用一次,并且调用级别尽可能高)。注意,我已经标记了 config 参数作为可选参数,因此您应该调用 福鲁特 即使您没有要传递的配置。

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

    这是我的记忆,因为我现在没有代码,所以如果出于任何原因它不起作用,请告诉我。

    推荐文章