EXCEPTION:无法读取未定义的属性'addInstrumentToStage'

时间:2017-01-09 16:24:54

标签: javascript angular

我有一个angular2个应用typescript,我正在使用ng2-dragula。 这是构造函数:

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的唯一奇怪之处在于,它正在注入另一项服务。那么,您认为嵌套依赖注入是否失败?

1 个答案:

答案 0 :(得分: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

我建议你看看如何引用正确的thisHow to access the correct `this` inside a callback?

这个很好的答案