有没有办法装饰以前在Angular中提供的服务 app.tokens.ts app.module.ts

我正在尝试扩展Angular库,但是我的库需要对其中一项服务进行特定设置才能正常工作。我希望可以以某种方式使用装饰器模式(而不是TypeScript装饰器)通过工厂重新提供服务。这将涉及将先前声明的服务注入工厂,并修改现有实现或返回使用原始版本的替代版本。看来我的工厂方法没有被调用。

export function decoratedTranslateServiceFactory(tranlateService: TranslateService) {
  // either make changes to translateService or return an 
  // alternate version that uses the original one 
  // (i.e. new MyTranslateService(translateService))
}

@NgModule({
  imports: [TranslateModule],providers: [
    { 
      provide: TranslateService,useFactory: decoratedTranslateServiceFactory,deps: [TranslateService] // <-- Same type as provided
    }
  ] 
})
export class MyTranslateModule {}
@NgModule({
  imports: [TranslateModule,MyTranslateModule]
})
export class AppModule {}

我希望TranslateService的修改版本(由我的模块提供的工厂提供)将是提供给应用程序其余部分的版本。我希望可以使用这种方法或类似的方法来扩展或包装现有服务。这有可能吗?

谢谢您的建议。

编辑:添加一个StackBlitz

wxc3344 回答:有没有办法装饰以前在Angular中提供的服务 app.tokens.ts app.module.ts

从您的代码来看,我认为没有调用您的工厂,因为您没有在代码中的任何地方未注入。仅导入包含该依赖性的模块是不够的

但是,如果调用了函数,则应该遇到一些与循环依赖相关的错误。

这是我的尝试:

app.tokens.ts

export class DecoratedService {
  static instance: DecoratedService;

  /* ... */

  constructor () { }

  /* ... */
}

export function decoratedServiceFactory () {
  console.warn('[DECORATING]');
  if (!DecoratedService.instance) {
    DecoratedService.instance = new DecoratedService();
  }

  const service = DecoratedService.instance;

  /* Decorate the service... */

  return service;
}

app.module.ts

/* ... */
{
  provide: DecoratedService,useFactory: decoratedServiceFactory,}
/* ... */

StackBlitz。 (向下滚动到最后一行

本文链接:https://www.f2er.com/3131367.html

大家都在问