2017-06-10 82 views
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: '<' 
     } 
    }; 

Here is the output of the console

的我用自耕农我的应用程序和支架的另一件事它具有的JSLint用的console.log禁止其说,你必须使用的角度。$日志,但事情的我不想改变,我想在这里理解这个问题。

+0

附加'/ * eslint无控制台:[ “错误”,{ allow:[“warn”,“error”]}] * /'在你的JS文件的第一行删除'console.log()'警告。 [参考](http://eslint.org/docs/rules/no-console) –

+0

是的,这是其他的解决方案,但我想明白为什么我不能在函数中使用$日志。 – Merlyn007

+0

你正在使用'this'里面的函数(torrent){...}来引用那个函数而不是类(这是你想要引用的那个)。在纯ES6中,您可以使用箭头函数而不是普通函数,以便此引用保持外部引用。 – DiegoRBaquero

回答

0

您或者需要引用此类(该类)作为在函数(torrent)函数内使用的另一个变量或使用箭头函数,以便该引用保持为第一类。

溶液1,使用另一个变量来REF类:

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); 
    }