0

此代码在使用提前编译的开发模式下失败。

export function loggerFactory(console, http, device, injector) {
  return environment.production ?
         new LogstashLoggerService(device, injector, http) :
         new ConsoleLoggerService(console);
};

let consoleObj = window.console;

@NgModule({
  imports: [],
  exports: [],
  declarations: [],
  providers: [],
})
export class LoggerModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: LoggerModule,
      providers: [
        {provide: CONSOLE, useValue: consoleObj},
        {
          provide: Logger,
          useFactory: loggerFactory,
          deps: [CONSOLE, HttpInterceptor, DeviceService, Injector]
        }
      ]
    };
  }
}

如何注入控制台?

4

1 回答 1

1

你必须使用useFactory任何你想为 AOT 注入的东西。查看粗斜体的变化。我添加了一个名为“控制台”的注入工厂。

import { Inject } from '@angular/core';

export function loggerFactory(@Inject('Console') console, http, device, injector) {
  return environment.production ?
         new LogstashLoggerService(device, injector, http) :
         new ConsoleLoggerService(console);
};


export function consoleFactory(): any {
    return console;
}


@NgModule({
  imports: [],
  exports: [],
  declarations: [],
  providers: [],
})
export class LoggerModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: LoggerModule,
      providers: [
        { provide: 'Console', useFactory: consoleFactory },
        {
          provide: Logger,
          useFactory: loggerFactory,
          deps: [CONSOLE, HttpInterceptor, DeviceService, Injector]
        }
      ]
    };
  }
}
于 2017-10-20T16:57:18.693 回答