2017-06-10 83 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); 
    }