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

Displaying a TypeScript-enabled antd tree component in a React application does not show any information

I attempted to convert the Tree example from antd to utilize TypeScript, however, the child-render function does not seem to return anything. The commented row renders when I remove the comment. The RenderTreeNodes function is executed for each element in ...

Why can't we import Angular 4 as a library similar to AngularJS?

Why was AngularJS introduced as a script to import in an HTML page? However, in the newer version Angular 4, we need to use a web server to launch the application? Is it because AngularJS is not considered a framework but Angular 4 is? Thank you. ...

Guide to easily printing a page in Angular 4 using TypeScript

When using my web app, there are certain pages where I need to print only a specific component without including the sidebar. I have written the following TypeScript code to achieve this: print() { window.print(); } The relevant HTML code begins with: & ...

The exploration of child routes and modules

I'm currently working on a somewhat large project and I've decided to break it down into modules. However, I'm facing an issue with accessing the routes of admin.module.ts. In my app.module, I have imported the admin Module. imports: [ Br ...

Transferring FormArray validators from a child component to a parent component in Angular version 8

UPDATE: I successfully implemented data passthrough and validation by refactoring the email-phone-input.component.ts to utilize ControlContainer, obtain the FormGroup from the parent component, and manage FormArray controls. Stay tuned for the updated repo ...

Add a hyperlink within a button element

I am looking to add a route to my reusable 'button' component in order to navigate to another page. I attempted using the <Link> </Link> tags, but it affected my CSS and caused the 'button' to appear small. The link works if ...

What is the best practice for Angular: running production build before or after testing?

When developing a Java application for production, I typically set up the build process to create the production artifacts first and then run tests against those artifacts. Recently, I joined an Angular project and noticed that the build process is struct ...

callback triggering state change

This particular member function is responsible for populating a folder_structure object with fabricated data asynchronously: fake(folders_: number, progress_callback_: (progress_: number) => void = (progress_: number) => null): Promise<boolean ...

What is the method by which the Material-UI Button component determines the properties for the component that is passed to the `component` prop

Could someone please clarify how Material-UI enhances the properties of its Button component by incorporating the properties of a specific component if passed in the component attribute? interface MyLinkProps extends ButtonBaseProps { someRandomProp: str ...

Is there a way to access the rootPath or other client-side information from the language server side?

I'm currently developing a language extension based on the example "language server" available at https://code.visualstudio.com/docs/extensions/example-language-server. In order to determine the current folder being used by vscode on the server side, ...

What is the process for integrating additional Firebase Cloud Functions into an Angular Universal project?

When working on an Angular Universal project, the fixed configuration for firebase.json looks like this: { "hosting": [{ "target": "PROJECT-ID", "public": "dist/PROJECT-ID/dist/PROJECT-ID/bro ...

Error: Invalid argument type

I'm encountering difficulties retrieving data from an API as I delve into learning Angular 2. The error message I am facing is: url.js:106 throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'url', 'string', url); Typ ...

Is there a way for me to access the data stored in session storage in Next.js?

One of the components in my project is a slider, which allows users to set the number of columns in an Image Gallery component. This code snippet shows the implementation of the slider component: export default function Slider({ value, handleChange }: ISl ...

Can an enum be declared in Typescript without specifying a type explicitly?

Within an interface, I have a group of 10+ (optional) members, most of which have a specific set of potential values. To streamline this, I would like to utilize enums. However, creating separate enum types for each member (which are only used once and hav ...

Safari 11.1 and Angular 9 - config object missing a defined key-value

While using Safari, I have encountered a problem in the Primeng input text field. When I type into the text box, errors are logged into the console. handleKeypress — injected.entry.js:8231TypeError: undefined is not an object (evaluating 'settin ...

The module '@angular/material' could not be located, please check for errors

An Issue Arises The module '@angular/material' cannot be located. In the file app.module.ts import { MaterialModule } from '@angular/material'; Find more information here: https://material.angular.io/guide/getting-started npm in ...

Struggling to grasp the error: "NDEFReader is not defined" in a Vue3 web application

In the process of developing a vue3 application, I am integrating the NFC Web API to facilitate reading and writing NFC Chips. My project utilizes typescript, vue routing, and pinia for smooth functionality. Everything runs smoothly when the application i ...

Setting up Datatable in Angular 2+ without relying on jQuery

I need assistance with initializing a datatable for a table that has a unique id. Can you provide guidance on the syntax to achieve this? Here is an example of my table structure: <table id="myDataTable"> <thead> <tr> ...

Differentiate between function and object types using an enum member

I'm currently experimenting with TypeScript to achieve narrowed types when dealing with index signatures and union types without explicitly discriminating them, such as using a switch case statement. The issue arises in the code snippet below when at ...

What is the best way to define multiple variables in ionic 2 using Angular2 and TypeScript?

I'm brand new to working with ionic2/Angular2/Typescript. My project involves creating a wheel with eight slices, but I'm struggling with how to declare multiple variables. In JavaScript, I've declared them like this: function rand(min, max ...