简体   繁体   English

从事件监听器中保存价值

[英]Saving Value from Event Listener

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.我正在制作一个访问 Spotify WebPlaybackSDK 以通过我的浏览器播放音乐的前端服务。 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.使用它的方法是从我的前端连接到 sdk,然后从 Spotify 调用 API,告诉它使用访问令牌、设备 ID 和跟踪 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.我的问题是,我没有同步方法来保存 Spotify 播放器应该返回给我的设备 ID,因为它是通过事件侦听器完成的。 Below is some code under the ngOnInit() method.下面是 ngOnInit() 方法下的一些代码。

(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.我的播放服务中有一个 playTrack() function 需要 device_id 但我不知道如何从事件侦听器中保存它。 I need to save it in my application so I can call the playTrack() method whenever I would like.我需要将它保存在我的应用程序中,以便我可以随时调用 playTrack() 方法。

You can create a Subject instance and emit it whenever ready event is triggered.您可以创建一个 Subject 实例并在触发 ready 事件时发出它。

Subscribe to OnMusicReady and get device_id.订阅OnMusicReady并获取 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);
      });
    })();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM