【问题标题】:EXCEPTION: Cannot read property 'addInstrumentToStage' of undefined例外:无法读取未定义的属性“addInstrumentToStage”
【发布时间】:2017-01-10 00:30:35
【问题描述】:

我有一个带有typescriptangular2 应用程序,我正在使用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 唯一奇怪的是,它正在注入另一个服务。那么,你认为嵌套依赖注入失败了吗?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    改变

     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 而不是胖箭头合成器时,您会丢失引用页面的this

    我建议你看看这个关于如何参考正确this:How to access the correct `this` inside a callback?的好答案

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多