【问题标题】:$log anonymous function angular js not working$log匿名函数角度js不工作
【发布时间】:2017-11-12 03:47:09
【问题描述】:

当我尝试在 webtorrent 的功能中记录一些数据时遇到问题。

我想记录 this.client.add 的一些值,但我无权访问。

了解这里发生了什么?

    import Webtorrent from 'webtorrent';

    class PlaylistController {
      /** @ngInject */
      constructor($http, $log) {
        this.log = $log;
        this.client = new Webtorrent();

        $http
          .get('app/playlist/playlist.json')
          .then(response => {
            this.Torrent = response.data;
          });
      }

      addTorrent(magnetUri) {
        this.log.log(magnetUri);

        this.client.add(magnetUri, function (torrent) {
          // Got torrent metadata!
          this.log.log('Client is downloading:', torrent.infoHash);

          torrent.files.forEach(file => {
            this.log(file);
          });
        });
        this.log.log('sda');
        this.log.log(this.client);
      }
    }

    export const playlist = {
      templateUrl: "app/playlist/playlist.html",
      controller: PlaylistController,
      bindings: {
        playlist: '<'
      }
    };

另一件事,我使用 yeoman 作为我的应用程序的脚手架,它有带有 console.log 禁止的 JSLint,它说你必须使用 angular.$log,但我不想改变它,我想了解问题在这里。

【问题讨论】:

  • 在 JS 文件的第一行添加 /*eslint no-console: ["error", { allow: ["warn", "error"] }] */ 以删除 console.log() 警告。 Reference
  • 是的,这是其他解决方案,但我想了解为什么我不能在函数中使用 $log。
  • 您正在使用 this inside function (torrent) { ... } 这将引用该函数而不是类(这是您要引用的那个)。在纯 ES6 中,您可以使用箭头函数而不是普通函数,以便 this 引用保持在外部。

标签: javascript angularjs anonymous-function webtorrent


【解决方案1】:

您要么需要将此(类)作为另一个变量引用以在函数(torrent)函数内使用,要么使用箭头函数以使此引用保持为类。

解决方案1,使用另一个变量来引用类:

addTorrent(magnetUri) {
    this.log.log(magnetUri);

    var that = this;

    this.client.add(magnetUri, function (torrent) {
      // Got torrent metadata!
      that.log.log('Client is downloading:', torrent.infoHash);

      torrent.files.forEach(file => {
        that.log(file);
      });
    });
    this.log.log('sda');
    this.log.log(this.client);
  }

解决方案 2,使用箭头函数:

addTorrent(magnetUri) {
    this.log.log(magnetUri);

    this.client.add(magnetUri, torrent => {
      // Got torrent metadata!
      this.log.log('Client is downloading:', torrent.infoHash);

      torrent.files.forEach(file => {
        this.log(file);
      });
    });
    this.log.log('sda');
    this.log.log(this.client);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多