我有一个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的唯一奇怪之处在于,它正在注入另一项服务。那么,您认为嵌套依赖注入是否失败?
答案 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
。
我建议你看看如何引用正确的this
:How to access the correct `this` inside a callback?