我正在构建通过官方JS SDK使用Deezer播放器的网络应用。我遇到的问题是我无法从Deezer事件订阅中访问我的Angular组件。箭头函数无法理解this
的上下文,因此我无法调用组件的方法并将值传递给它们。正确的方法是什么?
app.component.ts
// ...
declare var DZ;
// ...
export class AppComponent implements OnInit {
currentTrack: any = null;
constructor() {}
ngOnInit(): void {
DZ.init({
appId : '8',
channelUrl : 'https://developers.deezer.com/examples/channel.php',
player : {
onload : this.onPlayerLoaded
}
});
}
onPlayerLoaded() {
DZ.player.playAlbum(302127);
DZ.Event.subscribe('player_position', console.log);
DZ.Event.subscribe('current_track', (response) => {
// I would like to pass response.track to setCurrentTrack() there
});
}
setCurrentTrack(track) {
this.currentTrack = track;
}
}
index.html
// ...
<head>
<script type="text/javascript" src="https://e-cdns-files.dzcdn.net/js/min/dz.js"></script>
</head>
// ...
答案 0 :(得分:2)
为了帮助其他人,您应该.bind(this)
进行函数调用,因为很可能this
引用了DZ上下文而不是您的类:
ngOnInit(): void {
DZ.init({
appId : '8',
channelUrl : 'https://developers.deezer.com/examples/channel.php',
player : {
onload : this.onPlayerLoaded.bind(this) //Fix right here
}
});
}