2017-01-09 54 views
1

我有一個angular2應用程序typescript,我正在使用ng2-dragula。 這裏是構造:例外:無法讀取未定義的屬性'addInstrumentToStage'

constructor( private dragulaService: DragulaService, 
       private audioFinderService:AudioFinderService) {} 

然後ngOnInit():

public ngOnInit(): any { 

     this.dragulaService.setOptions('second-bag', { 

        moves: function (el, container, handle) { 

           var file=this.audioFinderService.audioGetter(); 
           this.audioFinderService.removeFromStage(); 

,並在線路this.audioFinderService.audioGetter();它抱怨:

error_handler.js:50 EXCEPTION: Cannot read property 'audioGetter' of undefined 

我試圖使在一個依賴注入的構造函數,但它似乎並不承認audioFinderService

這裏是AudioFinderService

@Injectable() 
export class AudioFinderService { 
     constructor(private playService:SelectedInstrumentsService,private http:Http) { } 
    } 

約AudioFinderService唯一奇怪的是,它被注入其他服務。那麼,你認爲,嵌套的依賴注入失敗了嗎?

回答

2

變化

moves: function (el, container, handle) {//<-- 'this' will refer to the function object 

           var file=this.audioFinderService.audioGetter(); 
           this.audioFinderService.removeFromStage(); 

moves: (el, container, handle)=> {//<-- 'this' will refer to the page 

           var file=this.audioFinderService.audioGetter(); 
           this.audioFinderService.removeFromStage(); 

的問題,當您使用function,而不是脂肪箭頭synthax,你失去的是指的在頁面this是。

我建議你看一看如何引用正確的this這個偉大的答案:How to access the correct `this` inside a callback?

相關問題