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

Develop a custom data structure by combining different key elements with diverse property values

Within my coding dilemma lies a Union of strings: type Keys = 'a' | 'b' | 'c' My desire is to craft an object type using these union keys, with the flexibility for assigned values in that type. The typical approach involves ...

What's the most effective method for transferring data to different components?

How can I efficiently pass a user info object to all low-level components, even if they are grandchildren? Would using @input work or is there another method to achieve this? Here is the code for my root component: constructor(private _state: GlobalSta ...

What is the process for dynamically loading a component by its name in Angular 2?

I am currently incorporating dynamic loading of angular components in my application by using the following code snippet. export class WizardTabContentContainer { @ViewChild('target', { read: ViewContainerRef }) target: any; @Input() TabCont ...

Automatically assign the creation date and modification date to an entity in jhipster

I am currently working on automatically setting the creation date and date of the last change for an entity in JHipster, utilizing a MySQL Database. Below is my Java code snippet for the entity: @GeneratedValue(strategy = GenerationType.AUTO) @Column(nam ...

Leverage the geocode callback function results from Google Maps in NodeJS to render a map on the AngularJS 2 component template

Hey there, I'm currently utilizing the Google Maps Node.js client web API and want to showcase a map on my HTML views using AngularJS 2. I have a server export that sends an object to my AngularJS2 client service const googleMapsClient = require(&ap ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

Tips for implementing cdkVirtualScroll in a basic single select mat-select:

I am attempting to improve performance by using cdkVirtualScroll with mat-select. <mat-select formControlName="name"> <cdk-virtual-scroll-viewport itemSize="42" [style.height.px]="5*42"> <mat-option ...

Angular - Javascript - Oops! The variable 'google' seems to have gone missing after reloading the page

For my website, I utilized Angular 2+ and integrated the Google Maps Api by adding the following code to my index.html file: <script async defer src="//maps.googleapis.com/maps/api/js?[myKey]&libraries=places"> </script> ...

Change the property value prior to running TypeScript validation

I possess the following object: const translations = { msg_hello: 'Hello', msg_bye: 'Bye' } In addition, I have a function that is structured as such: const generateTranslation = (partialKey: string): keyof typeof translations ...

Differences between Angular2 local template variables and Jade ID shortcutsIn Angular2, local

Angular2 has introduced the local template variable feature, which is created using #var. When using the Jade Template Engine, this syntax gets converted to #var="var". Is there a method to avoid this conversion? Otherwise, accessing the original local t ...

Having trouble retrieving a specific key from the state object in Redux using TypeScript

I have incorporated TypeScript into my Ionic project, using React hooks. I recently added an errorReducer to handle any errors that may arise from the server. Below is a snippet of my code: Action import { ERROR_OCCURRED } from "./types"; ...

Is it possible to use both interfaces and string union types in TypeScript?

My goal is to create a method that accepts a key argument which can be either a string or an instance of the indexable type interface IValidationContextIndex. Here is the implementation: /** * Retrieves all values in the ValidationContext container. ...

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

The issue arises when Jest fails to align with a custom error type while utilizing dynamic imports

In my project, I have defined a custom error in a file named 'errors.ts': export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, Error.prototype); this.nam ...

What's the process for deducing the default generic parameter from a function type?

Is there a way to extract the default type parameter of a function in order to make this statement compile successfully? const fails: string = "" as ReturnType<<T = string>() => T>; ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...

React approach for managing multiple combobox values

Currently, I'm working on a page where users can upload multiple files and then select the file type for each file from a dropdown menu before submitting. These 'reports' are the uploaded files that are displayed in rows, allowing users to c ...

What is the best way to create a sortable column that is based on a nested object within data.record?

I am utilizing jquery jtable to showcase some data in a table. I have been using the following code snippet for each field in the table to display the data and enable sorting: sorting: true, display: (data) => { return data.record.<whatever_value ...

Oops! Angular2 couldn't find a provider for HttpHandler

I have been working on implementing HttpCache through an interceptor. Below is the code snippet for caching-interceptor.service.ts: import { HttpRequest, HttpResponse, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http' import ...

Issue with migrating from Angular version 2.4.10 to 4.0.0

After attempting to update my application from Angular 2.4.10 to 4.0.0, I used the following command: "npm install @angular/common@next @angular/compiler@next @angular/compiler-cli@next @angular/core@next @angular/forms@next @angular/http@next @angular/pl ...