1

I have an angular2 app with typescript, and i am using ng2-dragula. Here is the constructor:

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

and then ngOnInit():

public ngOnInit(): any {

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

                  moves: function (el, container, handle) {

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

and in the line this.audioFinderService.audioGetter(); it complains that:

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

i tried to make a dependency injection in the constructor, but it seems that, it does not recognize the audioFinderService

Here is the AudioFinderService

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

The only wierd thing about AudioFinderService is that, it is injecting another service. So, do you think, nested dependency injection is failed?

eko
  • 39,722
  • 10
  • 72
  • 98
Jeff
  • 7,767
  • 28
  • 85
  • 138

1 Answers1

2

Change

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

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

to

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

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

The problem is when you are using function instead of fat arrow synthax, you are losing the this that is refering to the page.

I suggest you to take a look at this great answer on how to refer to the correct this: How to access the correct `this` inside a callback?

eko
  • 39,722
  • 10
  • 72
  • 98