Issue with subscribing to a shared service in Angular 2

I've encountered some challenges with BehaviorSubject while using a shared service across three components:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class StageEndService {

  private stageNumber = new BehaviorSubject<number>(0);
  private stageNumberPassed = new BehaviorSubject<number>(0);

  stageNumber$ = this.stageNumber.asObservable();
  stageNumberPassed$ = this.stageNumber.asObservable();

  announceStageNumber(num) {
    this.stageNumber.last(num);
  }

  announceStageNumberPassed(num) {
    this.stageNumberPassed.last(num);

  }
}

The first of the two components modifying values in the service is shown below:

import { StageEndService } from './../../../common/services/stage-end.service';

@Component({
...
providers: [StageEndService]
})

...
private value = 6;

constructor (private stageEndService: StageEndService) {

  this.stageEndService.announceStageNumber(value);

}

The second component, similar to the first one, changes the value of stageNumberPassed.

In the last component, my attempt to subscribe fails (the console.log returns 0):

import { StageEndService } from './../../../common/services/stage-end.service';

// there's no provider here since it's not necessary if I'm correct

 constructor(private stageEndService: StageEndService) {}

ngOnInit() {
  this.stageNumberSubscription = this.recruitmentEndService.stageNumber$.subscribe(response => {
  this.stageNumber = response;
});

I'm unsure where the problem lies. When I log the values passed to the function in the service, it provides the correct numbers. It may be worth noting that the last component where I'm trying to subscribe is several levels down from the first component where I initially set the new value.

Answer №1

Avoid adding the service separately to each component as this will create individual instances, making it impossible to facilitate communication between services.

Opt for a single provision of the service within the AppModule or a commonly shared parent component instead.

Answer №2

this.recruitmentEndService.stageNumber$.subscribe(response => {
  this.stageNumber = response;
});

needs to be changed to

this.stageEndService.stageNumber$.subscribe(response => {
  this.stageNumber = response;
});

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

Discover the seamless transformation of a class definition into a Vue 3 component definition utilizing the dazzling 'tc39' decorators

The proposed API in the tc39/proposal-decorators repository is significantly different from the previous decorators API. Although TypeScript 5 doesn't fully support the new API yet, it's only a matter of time before the old API becomes deprecated ...

Discover how Angular 8 allows you to access a method result from a child component in the parent component using ViewChild once the method has been called in the

In my child component, I have implemented two buttons as shown below: child-component.html <div> <button (click)="getFirstData()">First</button> <button (click)="getLastData()" >Last</button> </div> In child-com ...

Typescript: Issue encountered with Record type causing Type Error

When utilizing handler functions within an object, the Record type is used in the following code snippet: interface User { id: string; avatar: string; email: string; name: string; role?: string; [key: string]: any; } interface Stat ...

Designing a user interface for unlimited nested components with optional properties

I am currently working on creating an interface for the specific object type shown below. "Condition": { "And": { "Or": { "userData": [ { "name": "Alex", &q ...

Is there a way to create a stub for the given function using sinon?

Here is my test function: const customTestLibrary = require("./test"); describe("Initial Test", function() { it("should run the test function successfully", function(done) { customTestLibrary.execute(); done(); }); }); The te ...

Retrieve data from FileReader's onload event asynchronously in Javascript

Although this question has been asked numerous times before, I have reviewed the answers provided and still cannot get my code to work. I am working with Angular 2. I have input tags for file insertion. The file successfully reaches the component, but when ...

What steps can I take to ensure that Visual Studio replaces my JavaScript file during the TypeScript build process?

In my development process using Visual Studio to work on my TypeScript project, I have encountered an issue with the build process. I have a build.ts file that links to all of my other TS files and compiles them into one app.js file along with an associate ...

Concerning the utilization of the <mat-toolbar> element within Angular

Is the mat-toolbar in Angular going to persist across all components and pages of the application? Will it be present in every component throughout the application? <mat-toolbar color="primary"> <mat-toolbar-row> <span>Welcome to C ...

Tips for effectively overriding a method in typescript

Why is this.fullName appearing empty in the show() method? class Person { protected name: string = ""; constructor(name: string) { this.makeSir(name); } makeSir(name: string) { this.name = "sir" + name; } } class M ...

Make sure to pause and wait for a click before diverting your

Having an issue with a search dropdown that displays suggestions when the search input is focused. The problem arises when the dropdown closes as soon as the input loses focus, which is the desired functionality. However, clicking on any suggestion causes ...

Angular causing alignment issues for items not centered

I'm having trouble centering the contents of a div with my code. The properties I am applying don't seem to work. Any idea why this is happening? <div class='center'> <form (ngSubmit)="loginUser()" style="background: steel ...

invoking a function in one component from another component within an Angular 4 project using ng-smarttable

Utilizing ng-smarttable to display data in a table and have successfully added a custom button in a separate component. However, I am encountering an issue where the data does not reload when clicking on the button. An error message is appearing: ERROR Ty ...

Issue encountered when trying to bring in a component from a different module

I am attempting to import the 'OpenDialogContentComponent' component from Module A into Module B, however I am encountering this error: 'Cannot determine the module for class OpenDialogContentComponent in C:/Users/jitdagar/Desktop/TDP/pwt-u ...

Bringing in the component's individual module

I encountered the error message in my Angular application - Can't bind to 'formGroup' since it isn't a known property of 'form' - and managed to resolve it by including the import import { AddEditModule } from './add.edit ...

In Angular 5 HTTP GET request, the value "null" is being converted to ""null""

I'm currently in the process of transitioning our application from Angular 4 to Angular 5. In Angular 5, when passing an object model as parameters, if one of the values is null, it gets converted to a "null" string which is causing issues for us. Her ...

The angular.json file contains a script and a styles property

After encountering issues with adding styles and scripts to my angular.json file, I discovered that neither Bootstrap nor other scripts were taking effect. It turns out there are two places where you can define scripts and styles in the angular.json file a ...

Unable to locate the identifier 'BrowserWindow'

In the providers folder of electron.service.ts, I have the following code: import { Injectable } from '@angular/core'; // If you import a module but never use any of the imported values other than as TypeScript types, // the resulting javascrip ...

Generate a byte array in JavaScript

How can a byte array be created from a file in JavaScript (or Typescript) to send to a C# WebApi service and be consumable by the C# byte array method parameter? Could you provide an example of the JavaScript code? The context here is an Angular 4+ applic ...

Utilizing Logical Operators in Typescript Typing

What is the preferred method for boolean comparisons in Typescript types? I have devised the following types for this purpose, but I am curious if there is a more standard or efficient approach: type And<T1 extends boolean, T2 extends boolean> = T1 ...

The contents table remains fixed in the top right corner as you scroll

I have developed an Angular app with a table-of-contents component that only displays two items. The code for the script is as follows: ts import { Component, OnInit } from '@angular/core'; import { pdfDefaultOptions } from 'ngx-extended-p ...