【问题标题】:Made my own logger in angular2用angular2制作了我自己的记录器
【发布时间】:2016-06-17 07:20:31
【问题描述】:

我已经编写了记录器服务,但出现了一个我无法理解的错误。

下面是部分代码:

import { Injectable } from "@angular/core";
@Injectable()
export class LoggerService {
    private _log: Function;

    constructor() {
        this._log   = console.log;

        this.blockDefaultConsoleMethods();
    }

    public log(...args) {
        this._log(args);
    }

    private blockDefaultConsoleMethods() {
        console.log = console.info = console.warn = console.error = () => null;
    }
}

一个错误: TypeError: Illegal invocation

主要思想是弃用默认的控制台方法

【问题讨论】:

  • 错误出现在代码哪里?
  • @toskv 当我调用某个方法时
  • 您的示例中的哪一行代码?
  • 您如何调用该服务?你是怎么注射的?
  • 我在 bootstrap 方法中注入 logger 并在组件的构造函数中获取它们

标签: javascript typescript angular ecmascript-6 angular-services


【解决方案1】:

像这样直接调用console.log 是行不通的。您可以尝试像这样调用它:

import { Injectable } from "@angular/core";
@Injectable()
export class LoggerService {
    private _log: Function;

    constructor() {
        this._log   = console.log;

        this.blockDefaultConsoleMethods();
    }

    public log(...args) {
        Function.prototype.apply.call(this._log, console, args); // <--- change here
    }

    private blockDefaultConsoleMethods() {
        console.log = console.info = console.warn = console.error = () => null;
    }
}

以工作Plunker为例使用

【讨论】:

  • 直到第一次为特定选项卡打开开发人员工具时才会公开控制台对象。此外,console.log 是否期望内部有一个this 对象来访问它的对象的成员,而您没有像以前那样直接调用它。这就是为什么您需要像使用 Function.prototype.apply.call 一样为其添加上下文(请参阅 console 参数)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2015-01-29
  • 1970-01-01
相关资源
最近更新 更多