Receive the most recent information from Angular's service method

I offer a unique service.

handler.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 Handler {
  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) function updates with fresh data each time a user clicks to play an album or track. This can be observed in the last two functions. I have a queue component that should display the current playlist of tracks passed into the initTracks(tracks) method. My challenge lies in implementing this functionality. I have attempted using an observable of the tracks utilizing of(tracks) within the initTracks function without success. Additionally, I experimented with a Subject for subscription purposes, but also encountered issues. How can I successfully pass any new data sent to the initTracks(tracks) into the queue component? Thank you.

If required, here is the link to the current source code. source code

Answer №1

I recommend using ReplaySubject and let me know if it solves your issue. Would you be able to provide a snippet of code showing how you're emitting data and subscribing?

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

Rendering the D3 pie chart within *NgFor Angular should only occur once within the component

I am currently in the process of building a dashboard using Angular 8. To display charts, I have integrated d3.js. My goal is to render three pie charts within three separate sibling div elements. However, only the first div displays the pie chart while ...

What is the process for sending an http get request that provides a JSON array to populate an ngFor directive?

I'm trying to figure out how to make an http get request in order to retrieve a json array of data that I can use within an ngFor loop. The list that needs to be looped through is stored in this.list. Currently, the json file for testing purposes is l ...

The function this.listCatModel.push is not a valid operation

I have a dropdown that I want to populate using the following code: this.categoryService.GetListItem(this.GetAllcatListUrl).subscribe(data=>{ this.listCatModel=data, this.listCatModel.push({ id:0, name:'Main Category', parent ...

I am eager to perform DOM manipulation similar to jQuery but within the context of Angular 6

Is there a way to modify the background color of the main div when a button is clicked? <div> <p>I'd like to be able to change the background color of the parent div by clicking a certain button. </p> <button (click)=" ...

Exploring Angular: Understanding Events and Addressing the Error Message "subscribe is not a function"

Recently, I delved into the basics of Angular 4 and encountered a roadblock while trying to listen to an emitted event. Let me share a simple example that demonstrates the issue: DateSenderComponent is sending out the current date to be handled by its par ...

employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed. function checkUserExists(identifier) { let user ...

Can a component's route be dynamically changed based on its state?

Within an Angular 12 application, there exists a component known as SignUpComponent: export class SignUpComponent implements OnInit { form: FormGroup; result: boolean; constructor(private formBuilder: FormBuilder, private userService: UserService) ...

How can I access and modify a sub collection document in Angular Firestore?

I am facing a challenge in fetching a single document from a Firestore sub collection with the path: database/users/uid/animal/docID Although I have successfully parsed the docID from another component, I am struggling to retrieve the information to displ ...

Refresh Angular Component upon query parameter modification

Within my application, there is a search form that can be accessed by adding query parameters to the URL. This will prefill the form with specific information. My goal is to clear this prefilled state when the search icon in the navigation is clicked. Whi ...

Utilizing Array.every to refine a union of array types, narrowing down the options

I need to narrow down the type of a variable that is a union of different array types in order to run specific code for each type. I attempted to use Array.every along with a custom type guard, but encountered an error in TypeScript stating "This expressio ...

Updating an array in a single line of code in Javascript can be achieved

Can the code below be optimized? const item: any; // New data const index: number = basketModel.data.coupons.findIndex( (x: any) => x.couponId === item.couponId ); if (index === -1) { // If new item, push it to array ...

Is it possible for Angular 2 JWT to have an unauthenticatedRedirector feature?

Having transitioned from Angular 1 where JWT tokens were used for user authentication, I had the following code: .config(function Config($httpProvider, jwtOptionsProvider) { // Interceptor to add token to every $http request jwtOptionsProv ...

Creating an image using the @aws-sdk/client-bedrock-runtime package is a simple process

Having crafted a BedrockRuntimeClient using typescript, I'm stumped on how to call upon the model and execute the command. const client = new BedrockRuntimeClient({ region: "us-east-1", apiVersion: '2023-09-30', ...

What is the process of creating the /dist folder in an unreleased version of an npm package?

Currently working on implementing a pull request for this module: https://github.com/echoulen/react-pull-to-refresh ... It seems that the published module generates the /dist folder in the package.json prepublish npm script. I have my local version of the ...

Exploring Angular 4.3's HTTP Interceptor Retry功能

As I delve into my first attempt at coding, I find myself faced with the challenge of capturing 401 errors using HttpInterceptor. My goal is to generate a new auth token based on a certain condition and then retry the process with that token in place. Howe ...

The process of compiling and monitoring *two* Typescript packages, where one is reliant on the other

I'm in the process of creating a Typescript library located under src/ and sample files under examples/. The current directory structure is as follows: examples/ package.json exampleFiles.ts src/ index.ts package.json I am able to compil ...

The Angular2 promise resolves before the web service call has finished executing

I have a service in Angular 2 that contains a function responsible for providing data for a dropdown list. This particular function returns a promise. Below is the code snippet from the service: getStuff(): Promise<Stuff> { return t ...

Creating a component in Angular that utilizes multiple nested FormGroups

When attempting to nest multiple FormGroups, everything works smoothly if the template is not extracted into separate components. For instance, the following example functions as expected: Template <form [formGroup]="baseForm"> <div formGr ...

Updating Angular 7 ngrx state management without the need for explicit action types

After calling an ngrx action and saving the result in a local variable within a component, I noticed that if I edit this copy without saving it as well as taking any specific actions, when I leave the route, the store is automatically updated! Here is a s ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...