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

时间:2018-11-04 15:59:10

标签: javascript angular typescript ecmascript-6 console.log

我已经看到许多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
  }
}

2 个答案:

答案 0 :(得分:0)

如果要在控制台中查看Object,则应使用JSON.stringify()

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

答案 1 :(得分:0)

玩了一段时间之后。我发现这给了我想要的东西。

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