Tips on how to reach an Angular component within a third-party library

I'm currently working on a web application that incorporates the Deezer player through the official JS SDK. I've run into an issue where I am unable to access my Angular component from within the Deezer event subscription. The arrow function doesn't recognize the context of 'this', making it impossible for me to call my component's methods and pass values to them. How can I properly address this problem?

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) => {
            // Here lies the challenge of passing response.track to setCurrentTrack()
        });
    }

    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>

// ...

Answer №1

If you want to assist others, make sure to include .bind(this) in your function call because it is probable that this is now referring to the DZ context rather than your class:

ngOnInit(): void {
    DZ.init({
        appId  : '8',
        channelUrl : 'https://developers.deezer.com/examples/channel.php',
        player : {
            onload : this.onPlayerLoaded.bind(this)  //Ensure correct function binding here
        }
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate a hierarchical JSON object by transforming a tree structure - Enhanced script

I am currently working on building a JSON object that updates dynamically as a node tree is constructed. The node tree will take user input and add it to the tree, while also updating the JSON object with the values. Here's what the JSON object should ...

What could be the reason for axios yielding [object Promise] rather than the actual data?

My issue involves a function that retrieves data from an API. However, when I integrate this function into an EJS template, it returns a promise instead of the desired data. Strangely, when I console.log the data, it displays the correct information. Assi ...

The submission of the Jquery form is not successful

I am struggling with a form on my page. I want to disable the submit button and display a custom message when submitted, then use jQuery to actually submit the form. <form> <input type="text" name="run"/> <input type=&quo ...

Adding a specific element to an array using JQuery

I am in the process of developing a web application using jQuery to track goals and habits. Users can set a main goal such as 'Discipline' and then add sub-goals or habits related to that main goal (e.g. 'exercise every day'). Organizi ...

In order to make Angular function properly, it is crucial that I include app.get("*", [...]); in my server.js file

Recently, I delved into server side JavaScript and embarked on my inaugural project using it. The project entails a command and control server for my own cloud server, operating with angular, Expressjs, and bootstrap. Presently, I am encountering challeng ...

Is there a way for me to determine which .js script is modifying a particular HTML element?

Let's take a look at a specific website as an example: This particular website calculates value using a .js script embedded in the HTML itself. Upon inspecting the source code by pressing F12, we can locate the element containing the calculated valu ...

Can someone assist me with troubleshooting my issue of using a for loop to iterate through an array during a function call

Having recently delved into the world of Javascript, I've encountered a challenging problem that has consumed my entire day. Despite attempting to resolve it on my own, I find myself feeling quite stuck. The structure of my code is relatively simple ...

What is the best way to customize the styles of a reusable component in Angular2?

I am working with a reusable component called "two-column-layout-wrapper" that has its styles defined in the main .css file. In another module, I need to use this component but customize the width of two classes. How can I override these styles? import ...

Right-click context menu not working properly with Internet Explorer

Seeking assistance with extracting the URL and title of a website using JavaScript. The script is stored in a .HTM file accessed through the registry editor at file://C:\Users\lala\script.htm Below is the script: <script type="text/java ...

JavaScript facing issue with $.get command executing in incorrect order

I have encountered an issue with my JavaScript code where it is not running in sequence. The script includes an unload function that uses the $.get jQuery command to fetch a file, which is then supposed to be printed to an external device. To debug this ...

Firing a custom jQuery event when a page loaded via AJAX is complete, ensuring it is triggered

I am facing an issue with a particular scenario. There is a page that contains a script to load a child page and log a custom event, which is triggered in a Subform. --Index.html-- <body> <input type="button" class="clickable" value="Load child ...

Incorrect posture during the movements

Utilizing Jquery Drag and Drop, I have implemented two swap-able divs. However, during the animation process of swapping the divs, their positions are not properly maintained. The actual swapping of the divs works correctly, but there is an issue with the ...

Guide on transforming Json information into the preferred layout and iterating through the loop

Currently, I am diving deep into the world of JSON and feeling a bit puzzled by data formats, arrays, objects, and strings. First things first, I'm in need of data structured like this (on a jQuery page). Would this be considered an object or an arra ...

The 'string' data type cannot be assigned

Let me share how I define and utilize my font sizes in my custom React app: FontSizes.ts const fontSizes = { xs: 'xs', sm: 'sm', base: 'base', lg: 'lg', xl: 'xl' ...

Executing the beforeRouteLeave navigation guard on a vue component for testing purposes

I am facing a challenge with unit testing the routing behavior of a vue component using jest. Specifically, when navigating away from the component, the 'beforeRouteLeave' guard in Vue-router is not triggering during testing, even though it works ...

What is the best way to use jQuery to filter data in a table by clicking on a specific table row?

My website contains a table with player names and servers, but I want to make them clickable for filtering purposes. For instance, clicking on a player name should reload the leaderboards to show which servers that player plays on, and clicking on a server ...

Unable to connect to 'watchedLabels' as it is not a recognized attribute of 'section' in the Angular angular-scroll-spy plugin

Encountered an issue while trying to use 'angular-scroll-spy'! Error NG8002: Unable to bind to 'spiedTags' as it is not recognized as a property of 'div'. This code is from an .html file <div *ngIf="candidate_output; ...

Tips for integrating error management in Angular with RXJS

Implementing error handling in the use case method by using subscriptions is my goal. When an error occurs in the adapter, the handling should be done in the use case. However, in the code snippet provided below, the catch block does not seem to work pro ...

Utilize Array.filter to retrieve specific values based on a defined number of elements

I have a function that currently retrieves the url value for each item in an array up to a specified maximum number. Below is the code snippet: const myArray = [ { url: "example.com/1", other: "foo" }, { url: "example.com/s ...

When the loop is malfunctioning due to a certain condition

what happens if the condition in the controller file is not executed during runtime... ...