簡體   English   中英

如何從第三方庫訪問角度分量

[英]How to access angular component from 3rd party library

我正在構建通過官方JS SDK使用Deezer播放器的網絡應用。 我遇到的問題是我無法從Deezer事件訂閱中訪問我的Angular組件。 Arrow函數不了解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>

// ...

為了幫助其他人,你應該.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
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM