0
votes

I have a problem in the way I am architecting my code.

I am making a front end service that accesses the Spotify WebPlaybackSDK to play music through my browser. The way to use this is to connect to the sdk from my frontend, then call an API from Spotify that tells it to play a song from a device using an access token, device id, and track uri.

My problem is, I have no synchronous way to save the device id that the Spotify player is supposed to give back to me because it is done through an event listener. Below is some code under the ngOnInit() method.

(async() => {
        const { Player } = await this.playbackService.loadPlaybackPlayer();
        const sdk = new Player({
          name: "Web Playback SDK",
          volume: 1.0,
          getOAuthToken: callback => { callback(access_token); }
        });
        
        this.playbackService.connectPlayer(sdk);
        sdk.addListener('ready', ({device_id}) => {
          
        })
      })();

I have a playTrack() function inside my playbackService that requires the device_id but I do not know how to save it from an event listener. I need to save it in my application so I can call the playTrack() method whenever I would like.

1

1 Answers

0
votes

You can create a Subject instance and emit it whenever ready event is triggered.

Subscribe to OnMusicReady and get device_id.

  device_id;
  OnMusicReady = new Subject();

  ngOnInit() {
    this.OnMusicReady.subscribe(device_id => {
      console.log('Device ID: ' + device_id);
      this.device_id = device_id;
      // Perform additional logic here.
    });
    this.initSpotify();
  }

  initSpotify() {
    (async () => {
      const { Player } = await this.playbackService.loadPlaybackPlayer();
      const sdk = new Player({
        name: 'Web Playback SDK',
        volume: 1.0,
        getOAuthToken: callback => {
          callback(access_token);
        }
      });

      this.playbackService.connectPlayer(sdk);
      sdk.addListener('ready', ({ device_id }) => {
        // Store device_id in the class variable.
        this.OnMusicReady.next(device_id);
      });
    })();
  }