使用 console.info.bind 时的控制台日志对象(控制台)

Console Log objects when using console.info.bind(console)

我看到许多 Angular2+ 开发人员使用 console.info.bind(console) 方法从 javascript 控制台记录器中创建记录器服务。但是,在我的实现中,我所有的 javascript 对象都被注销为 [object object].

如何调整我的记录器以便在我的控制台中呈现我的对象?

ConsoleLogger.service.ts

import {Injectable} from '@angular/core';
import {environment} from '../../../environments/environment';

import {Logger} from './logger.service';

export let isDebugMode = environment.isDebugMode;

const noop = (): any => undefined;

@Injectable()
export class ConsoleLoggerService implements Logger {
  get info() {
    if (isDebugMode) {
      return console.info.bind(console);
    } else {
      return noop;
    }
  }

  get warn() {
    if (isDebugMode) {
      return console.warn.bind(console);
    } else {
      return noop;
    }
  }
}

Logger.Service.ts

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

export abstract class Logger {
  info: any;
  warn: any;
}

@Injectable()
export class LoggerService implements Logger {
  info: any;
  warn: any;
}

Example.Component.ts

import {Component, OnInit} from '@angular/core';
import {LoggerService} from 'src/app/core';


@Component({
  selector: 'app-example-component',
  templateUrl: 'example.component.html',
  styles: ['example.component.scss']
})
export class ExampleComponent implements OnInit {
  exampleObject: {a: 'apple'; b: 'banana'};
  constructor(
    private _logger: LoggerService,
  ) {
  }

  async ngOnInit() {
   this._logger.info("Example Output: " + this.exampleObject);
   // Example Output: [object object]
   // ?? i want to see the actual object
  }
}

如果你想在控制台中看到对象,你应该使用 JSON.stringify()

 return console.info.bind(JSON.stringify(console));

玩了一会儿。我发现这给了我想要的东西。

this._logger.info('Example: ', this.exampleObject);