Angular 4 使用 AOT 注入控制台

Angular 4 inject console with AOT

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

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]
        }
      ]
    };
  }
}

如何注入控制台?

对于要为 AOT 注入的任何内容,您必须使用 useFactory。查看粗体斜体的变化。我添加了一个名为 "Console".

的注入工厂
import { Inject } from '@angular/core';

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

<em><strong>
export function consoleFactory(): any {
    return console;
}
</em></strong>

@NgModule({
  imports: [],
  exports: [],
  declarations: [],
  providers: [],
})
export class LoggerModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: LoggerModule,
      providers: [
        <em><strong>{ provide: 'Console', useFactory: consoleFactory }</em></strong>,
        {
          provide: Logger,
          useFactory: loggerFactory,
          deps: [CONSOLE, HttpInterceptor, DeviceService, Injector]
        }
      ]
    };
  }
}