0

当我尝试在 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 作为我的应用程序的脚手架,它有 JSLintconsole.log禁止使用,它说你必须使用angular.$log,但我不想改变它,我想了解这里的问题。

4

1 回答 1

0

您要么需要将此(类)引用为另一个变量以在函数(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);
  }
于 2017-07-10T16:18:59.097 回答