Alf Moh
Alf Moh

Reputation: 7427

Get updated data from service method Angular

I have this service.

playerhandler.ts

import { Observable,of,Subject } from 'rxjs';
import { PlayerService } from "./../../core/services/player.service";
import { Injectable } from "@angular/core";
import { DeezerService } from "../services/deezer.service";
import { Track } from "../models/Track";

@Injectable({
  providedIn: "root"
})
export class PlayerHanlder {
  isPlaying: boolean = false;
  index: number;

  constructor(
    private playerService: PlayerService,
    private deezer: DeezerService
  ) { }

  initTracks(tracks): void {
    this.playerService.init(tracks);
  }

  play() {
    this.isPlaying = true;
    this.playerService.play();
  }

  pause() {
    this.playerService.pause();
  }

  stop() {
    this.playerService.stop();
  }

  next() {
    this.playerService.playNext();
  }

  previous() {
    this.playerService.playPrevious();
  }

  playing(playing) {
    this.isPlaying = playing;
  }

  onEnd() {
    this.playerService.playNext();
  }

  start(album) {
    if (this.isPlaying) this.stop();
    this.deezer.getTrackList(album.tracklist)
      .subscribe((tracks: Track[]) => {
        this.initTracks(tracks);
        this.playerService.index = 0;
        this.play();
      });
  }

  startSelectedTrack(tracks,trackIndex) {
    if (this.isPlaying) this.stop();

    this.initTracks(tracks);
    this.playerService.playNew(trackIndex);
    this.isPlaying = true;
  }
}

The initTracks(tracks) method gets a fresh data anytime a user clicks to play an album or clicks to play a particular track. This can be seen in the last two methods. Now, I have a queue component that is supposed to get the tracks data that is passed into the initTracks(tracks) method so that, the current playlist of tracks will be shown in the queue component. This is where I'm having the problem implementing. I have tried to create an observable of the tracks using of(tracks) in the initTracks method. That didn't work out. I've also tried using a Subject so that the tracks can be both subscribe and be subscribed but that also didn't work out. Please, how do I get any fresh data that is sent into the initTracks(tracks) method into the queue component. Thank you.

If needed, this is the current source code. source code

Upvotes: 1

Views: 138

Answers (1)

Vugar Abdullayev
Vugar Abdullayev

Reputation: 2085

Please use ReplaySubject and inform if helped. Can you post some example code where you emit data and subscribe?

Upvotes: 1

Related Questions