I'm building web app which uses Deezer player by official JS SDK. The problem I met is that I cannot access my Angular component from Deezer event subscription. Arrow function doesn't understand context of this
, so I cannot call my component's methods and pass values to them. What is correct way to achieve that?
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>
// ...
In order to help other individuals, you should .bind(this)
to your function call because its likely that this
is referring to the DZ context and no longer your class:
ngOnInit(): void {
DZ.init({
appId : '8',
channelUrl : 'https://developers.deezer.com/examples/channel.php',
player : {
onload : this.onPlayerLoaded.bind(this) //Fix right here
}
});
}