Encountering an error message in Angular stating "Spotify is not defined" while utilizing "@types/spotify-web-playback-sdk"

I'm currently integrating Spotify's web player SDK into an Angular project. I followed the steps outlined in this particular question and answer: Installing the types package, then including the types reference at the beginning of the file where I'm utilizing the Spotify namespace

npm install --save @types/spotify-web-playback-sdk

and

///  <reference types="@types/spotify-web-playback-sdk"/>

as the initial line in the file.

Here's a snippet of my code:

//class variable
spotifyPlayer: Spotify.Player | null = null

and


createWebPlayer(){
    const accessToken = this.authObject.access_token
    this.spotifyPlayer = new Spotify.Player({ //line 107
      name: 'Web Playback SDK Quick Start Player',
      getOAuthToken: cb => {
        cb(accessToken)
      },
      volume: 0.5
    })

    //ready
    this.spotifyPlayer!.addListener('ready', ({ device_id }) => {
      console.log('Ready with Device ID', device_id);
    });
  
    // Not Ready
    this.spotifyPlayer!.addListener('not_ready', ({ device_id }) => {
      console.log('Device ID has gone offline', device_id);
    });
}

The code compiles without errors, but I encounter the following error when calling createWebPlayer():

ERROR ReferenceError: Spotify is not defined
    createWebPlayer home.component.ts:107

I'm manually calling the function and ensuring I have an access token before doing so, so that shouldn't be the issue; I'm quite puzzled by this.

Things I've tried

I attempted to include an import statement like this:

import * as Spotify from 'spotify-web-playback-sdk'

However, I receive an error stating that it's not a module. The only installation I did was running

npm install --save @types/spotify-web-playback-sdk

I also experimented with changing line 107 to

this.spotifyPlayer = new window.Spotify.Player({

but encountered a similar error:

ERROR ReferenceError: window.Spotify is not defined
    createWebPlayer home.component.ts:107

I'm genuinely baffled and feel like I might be overlooking something obvious. Any assistance would be greatly appreciated!!

Answer №1

After troubleshooting, I believe I have resolved the issue. I discovered from this angular project on GitHub that I needed to include a script in the HTML page. It seems that the types file serves to prevent type errors rather than directly linking to the code.

The code snippet I borrowed from the mentioned project is as follows:

const script = document.createElement('script');
script.src = 'https://sdk.scdn.co/spotify-player.js';
script.type = 'text/javascript';
script.addEventListener('load', (e) => {
  console.log(e);
});
document.head.appendChild(script);
window.onSpotifyWebPlaybackSDKReady = () => {
  console.log('The Web Playback SDK is ready. We have access to Spotify.Player');

My updated code now appears like this:

createWebPlayerTwo () {
const script = document.createElement('script')
script.src = 'https://sdk.scdn.co/spotify-player.js'
script.type = 'text/javascript'
script.addEventListener('load', e => {
  console.log(e)
})
document.head.appendChild(script)
window.onSpotifyWebPlaybackSDKReady = () => {
  console.log(
    'The Web Playback SDK is ready. We have access to Spotify.Player'
  )
  const accessToken = this.authObject.access_token
  this.spotifyPlayer = new Spotify.Player({
    name: 'Web Playback SDK Quick Start Player',
    getOAuthToken: cb => {
      cb(accessToken)
    },
    volume: 0.5
  })

  this.spotifyPlayer.addListener('ready', ({ device_id }) => {
    console.log('Ready with Device ID', device_id)
  })

  this.spotifyPlayer.addListener('not_ready', ({ device_id }) => {
    console.log('Device ID has gone offline', device_id)
  })

  this.spotifyPlayer.addListener('initialization_error', ({ message }) => {
    console.error(message)
  })

  this.spotifyPlayer.addListener('authentication_error', ({ message }) => {
    console.error(message)
  })

  this.spotifyPlayer.addListener('account_error', ({ message }) => {
    console.error(message)
  })

  this.spotifyPlayer.connect()
  console.log('hi')
}

}

and I'm happy to report that it's functioning correctly! I am receiving the message "Ready with Device ID 13b20fd9..."

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

Challenges arise with dependencies during the installation of MUI

[insert image description here][1] I attempted to add mui styles and other components to my local machine, but encountered a dependency error. How can I resolve this issue? [1]: https://i.stack.imgur.com/gqxtS.png npm install @mui/styles npm ERR! code ERE ...

Encountering a crash when trying to create a form within a subscription in Angular 2 due to the formGroup being

I have data stored in my Firebase database that I want to use in a form using FormBuilder. Although it generally works fine, I often encounter errors saying formGroup expects a FormGroup instance. Please pass one in.. What confuses me is that the error oc ...

What is the most efficient way to trigger an API call using Angular HttpClient in response to multiple events without repetitively subscribing to the API call method throughout my code?

In my Angular Cli app, I have a data table with dynamic filters and a search bar. Whenever the search value changes, pagination changes, or a filter is applied or removed, I need to update the table items and filter information by making an API call. My s ...

How can I receive updates when an interface changes in Angular?

I'm attempting to subscribe to my interface and monitor for any changes, but I keep encountering errors. Fetching data from the API and assigning it to this.candidateProfile : export interface CandidateProfile { about: string, c_id: {}, cer ...

Showing nested arrays in API data using Angular

I would like to display the data from this API { "results": [ { "name": "Luke Skywalker", "height": "172", "mass": "77", & ...

What is the best way to eliminate Bootstrap from an Angular project?

When running my Angular project, I noticed that _reboot.scss is being uploaded and overwriting the styles of Angular Material. I attempted to remove it by following these steps: npm uninstall bootstrap Remove links from package.json Remove links from ang ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

Exploring Angular's View Encapsulation with Third-Party Libraries

When I integrate an external component into my own, I face a challenge with styling due to Angular View Encapsulation. Any CSS I define in my component does not affect the external component used in my HTML template. To work around this issue, I have set e ...

Angular CLI's selection of third-party libraries that are not available on npm repositories

Currently in the process of migrating an app from Angular 2 to Angular CLI Now facing the challenge of importing 3rd party libraries like orbitcontrols.js that are not available on npm or bower. After researching on https://github.com/angular/angular-cli ...

What is the best way to configure Winston with Webpack?

I'm working on an electron application that utilizes node.js and I want to integrate the Winston logging library. After adding Winston to my package.json file, I encountered warnings from the colors.js dependency when running the webpack build command ...

Ways to eliminate Typescript assert during the execution of npm run build?

How can I effectively remove Typescript asserts to ensure that a production build generated through the use of npm run build is free of assertions? Your assistance is appreciated ...

Setting up SSH keys for git to use outside of Git Bash

As someone who is relatively new to git and primarily uses Windows for programming, I recently set up a React app using create-react-app. To deploy it on my github.io project page, I utilized gh-pages. Setting up an SSH key on my local machine and adding i ...

Discovered a total of 11 minor vulnerabilities within a React Native Project

Every time I start a new React Native project using react-native init <projname>, and then attempt to install any necessary NPM Package, I always encounter this issue - identified 11 low severity vulnerabilities How can I resolve this problem? ...

Navigating the complexities of Angular 2+ modules, exports, and services: preventing duplication of shared/reusable services

Imagine if I have the following scenario: I have imported import { HttpModule } from '@angular/http'; into my main application module (BrowserModule). In my application, I am using the Http service through dependency injection in various parts of ...

Implementing setState callback in TypeScript with React Hooks

Hello everyone! I am currently working on defining my component types using TypeScript, and I am faced with a challenge. I am trying to set it up so that I can either pass an array of objects or a callback function containing the previous state. Below is t ...

Combining values in an Angular project to create a new object with the same properties using TypeScript

Hey there! I hope your day is going well. I'm currently working on calculating multiple objects to create a new one with average values. Here's the schema: export class stats{ assists:number causedEarlySurrender:boolean champLevel:numb ...

Creating a standard change listener for text entry fields utilizing Typescript and React with a dictionary data type

I came across an interesting example of using a single change function to manage multiple text inputs and state changes in React and Typescript. The example demonstrates the use of a standard string type: type MyEntity = { name: string; // can be app ...

Is it possible to utilize TypeScript for enforcing type safety in AngularJS templates?

Is it possible to utilize TypeScript in Angular 1.6 templates, following best practices such as components/bind-to-controller usage? Consider the following template code: <div>{{$ctrl.children[0].name}}</div> If we know the type of the contr ...

Building Angular CLI Applications with Separate SCSS Files for Browser Loading

Below is how I am importing the scss file: import { Component, OnInit, ViewEncapsulation } from '@angular/core'; @Component({ ...., styleUrls: ['../../scss/dashboard_admin.scss'], encapsulation: ViewEncapsulation.None }) e ...

Error message: "npm start cannot locate package.json file, even though the file is present

As I attempt to execute npm start within my Node.js project directory, I am facing a challenge. Despite having the package.json file in the correct location (C:\Myfirstproject\Vinci\Projet_Web), I keep encountering an error message that read ...