Sometimes, the Angular BehaviourSubject seems to only be triggered on select occasions

In my setup, there is a component named Database along with a Service called DatabaseService.

The current database status is stored in a BehaviourSubject and I need to access this status from the App Component.

To achieve this, I subscribe to the BehaviourSubject within the app.component.ts.

When I fetch the initial value using the BehaviourSubject, everything works as expected. However, if I trigger the .next() method from the database component, the updated value is not reflected in the app component.

I attempted moving the call to .next() inside a method within the database service, but unfortunately, it did not solve the issue.

Database.component.ts

@Component({
  selector: 'app-database',
  templateUrl: './database.component.html',
  styleUrls: ['./database.component.scss'],
  providers: [DatabaseService]
})


export class DatabaseComponent implements OnInit, OnDestroy {

  ...

  constructor(
      private databaseService: DatabaseService,
  ) {
  }

  ngOnInit(): void {
    ...
  }

  updateDatabaseStatus(): void {
    this.databaseService.databaseStatus.next(this.StatusId.value);
  }

  ngOnDestroy(): void {
    ...
  }
}

database.service.ts

@Injectable({
    providedIn: 'root'
  })
export class DatabaseService {

    public databaseStatus = new BehaviorSubject<DatabaseStatus>(DatabaseStatus.Open);

    constructor(private api: ApiService) {
      this.getSettingsDatabaseStatus().subscribe(data => {
        this.databaseStatus.next(data[0].statusId);
      });
    }

    public getSettingsDatabaseStatus(): Observable<Status> {
      ...
    }

    public updateCurrentDatabaseStatus(status: DatabaseStatus): void {
      this.databaseStatus.next(status);
    }
}

app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit, OnDestroy {


  public databaseStatus = 'Open';

  constructor(public router: Router,
              private _api: ApiService,
              private databaseService: DatabaseService) {
  }

  ngOnInit(): void {

    this.databaseService.databaseStatus.subscribe(status => {
      this.databaseStatus = DatabaseStatus[status];
    });
  }

  ngOnDestroy(): void {
    ...
  }
}

Answer №1

The issue arises from the creation of multiple instances of the DatabaseService.

When you specify providedIn: 'root' in your database service, it signifies that a single instance of the service will be generated at the application's root level, making it accessible to all components.

However, within your database.component, by including providers: [DatabaseService], a new and distinct local instance of the service is created exclusively for that component's use.

It would be advisable to eliminate this code from your database.component and only provide the service at the root level.

Additionally, ensure that calls to the .next() function originate solely from the database service.

In the revised implementation of your database.component:

@Component({
  selector: 'app-database',
  templateUrl: './database.component.html',
  styleUrls: ['./database.component.scss']
})


export class DatabaseComponent implements OnInit, OnDestroy {

  ...

  constructor(private databaseService: DatabaseService) {
  }

  ngOnInit(): void {
    ...
  }

  updateDatabaseStatus(): void {
      this.databaseService.updateCurrentDatabaseStatus(this.StatusId.value);
  }

  ngOnDestroy(): void {
    ...
  }
}

You can keep the current structure of your app.component and DatabaseService unchanged.

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

What steps can be taken to implement jQuery within an Angular 15 npm package?

In my development process, I often create my own npm packages using Angular and Typescript. One of the packages I am currently working on is a PDF viewer service, which includes a file named pdf-viewer.service.ts with the following code: import { Behavior ...

Error occurred during the Uglify process: Unable to access the 'kind' property as it is undefined

I developed a project using TypeScript (version 3.9.3) and Node (version 10.16.3), but now I want to minify the code by converting it to JavaScript and running UglifyJS. However, after going through this process, the services that were functioning properly ...

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 ...

Using an asynchronous for loop to assign a background image to a div element

I am facing an issue with setting the background image of an observable array in my Ionic application. Here is the code snippet I am using: <ion-card *ngFor="let picture of pictures$ | async;" <div class="user-image" [ngStyle]="{'background- ...

Error Encountered: Angular 2 ngOnInit Method Being Executed Twice

Encountered an unusual error in Angular 2 while working on two components that share similarities in templates and services. Here is a breakdown of how they function: Component: data: any; constructor(private _service: TheService) {} ngOnInit() { t ...

Error in Angular: trying to access property 'genre' of an undefined object

I am currently developing a simple app inspired by a tour of heroes (official angular tutorial). However, I have encountered an issue that I cannot seem to resolve, possibly due to my lack of understanding in basic programming concepts. Here is the code s ...

get the desired value from the array in typescript

Can someone help me extract all the type values in Angular 4 from the code snippet below? console.log('rows', this._column); rows 0: {name: "...", type: "string", ...} 1: {name: "...", type: "string", ...} 2: {name: "...", type: "datetime", .. ...

Angular 13 - Encountering issue with "Cannot access properties of null (reading 'getParsed')"

Currently working on a new Angular 13 project and running into an error: TypeError: Unable to access properties of null (reading 'getParsed') at .../main.2506c840be361c93.js:1:325924 at Array.filter () at nd._getActiveElements (.../main.2506c84 ...

What is the best way to customize the styles of a reusable component in Angular2?

I am working with a reusable component called "two-column-layout-wrapper" that has its styles defined in the main .css file. In another module, I need to use this component but customize the width of two classes. How can I override these styles? import ...

Incorporating regular expressions to extract a specific string from a URL is a requirement

Can anyone assist with extracting a specific string using regex in TypeScript? I have the following URL: https://test.io/content/storage/id/urn:aaid:sc:US:8eda16d4-baba-4c90-84ca-0f4c215358a1;revision=0?component_id=e62a5567-066d-452a-b147-19d909396132 I ...

Excluding the decimal point from version 1.0 in an API response with Angular 5

When working with Angular 5, I encountered an issue where the API response was returned as 1.0, but when displayed in the HTML field it only showed as 1. Upon inspecting the response in Chrome dev-tools, under the Network tab -> Response, it correctly ...

What are some effective ways to exclude multiple spec files in playwright?

Within my configuration, I have three distinct projects. One project is responsible for running tests for a specific account type using one login, while another project runs tests for a different login. Recently, I added a third project that needs to run t ...

Testing Angular application with a currency pipe results in an error stating "currency

Utilizing the built-in angular currency pipe in my components works perfectly fine. However, when attempting to unit test my component, an error occurs: https://i.stack.imgur.com/J18JL.png I am using Angular 10 with Ivy and have imported the CommonModule, ...

Having trouble with resolving a POST call in redux observable

Currently, I am developing a react native application and facing an issue with a POST call using Observable.fromPromise. The response that I receive is shown below, but I am struggling to capture the response in my code and also encountering some warnings. ...

Exploring nested JSON responses in Angular 2 with TypeScript

Below is the JSON response I received from the REST endpoint: {"image_2_11_0-51-upgrade.iso": {"model": "somemodel", "hostnames": ["abc.com", "abcd,com"], "upload_status": false, "version": "2.11.0-51"}, "image_2_11_0-51-upgrade.iso": {"model": "newmo ...

Add flexible templates into List element in Ionic version 3

My Progress Being a newcomer to ionic, I successfully created a List component in ionic 3 that retrieves JSON data from the server and displays it as a list layout on specified pages using a list selector. Objective I am looking to showcase various list ...

Is it necessary to reload the page each time to see updates on the navbar in nextjs?

I recently developed a Next.js application with a Navbar component integrated into my layout.tsx file. The challenge arises when a user logs in and is redirected to the home page, which showcases a link in the Navbar for viewing their profile. However, I n ...

Utilizing a powerful combination of Angular 5, PrimeNG charts, Spring Boot, and JHipster

I am facing an issue with creating charts using PrimeNG. The main challenge I'm encountering is the conversion of data from a REST API in Angular 5 (TypeScript) and retrieving the list of measurements from the API. I have an endpoint that returns my m ...

Generate a customizable form by utilizing a JSON file as a template. The JSON file can be easily modified by clicking a button, allowing for real-time

My goal is to develop a dynamic form using the guide provided at https://angular.io/guide/dynamic-form. I am utilizing two JSON files, namely sbb.json and gx.json. The initial creation of the form from the JSON file works flawlessly. However, I encountered ...

Is there a way to access the Stencil Web Component beneath Ionic/Angular?

In my Ionic 6/Angular 10 app, I am facing an issue with the ngAfterViewInit() callback being fired before the DOM is fully rendered. This results in inaccurate size queries during this callback. I have been searching for a callback that signals when the re ...