Tracking changes of a value emitted from one component to another in Angular can be achieved by using event emitters. By

Component A displays the current notification count. Meanwhile, Component B is responsible for receiving and updating the live count of notifications which are emitted and subscribed to in Component A. Interestingly, the count only updates when a page transition occurs.

To summarize what I'm trying to achieve:

Component B

ngOnInit(){
 this.handleRealTimeCount();
}

handleRealTimeCount() {
  this.countSvc
    .getCount()
    .subscribe((res: any) => {
      this.countSvc.setCount(
        res.count
      );
    });
}

Component A

this.getUnreadCount();
}

getUnreadCount() {
  this.countSvc.unreadCount.subscribe((res) => {
    this.notificationsCount = res;
  });
}

Within my Count Service, I utilize EventEmitter variables like so:

export class CountService {
  unreadCount = new EventEmitter();

  setCount(count) {
    this.unreadCount.emit(count);
  }

I am seeking advice on how to ensure that the real-time count updates whenever a new notification is received.

Answer №1

Have you considered using BehaviorSubject instead of EventEmitter?

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class CounterService  {   
  constructor() { } 
  private valueSource = new BehaviorSubject(0);
  countValue = this.valueSource.asObservable();
  setValue(value: number) { this.valueSource.next(value)}    
}

Answer №2

You're nearing the solution. My recommendation is to implement a BehaviourSubject in the service instead of an EventEmitter, and connect directly in your components' templates using the async pipe.

The Service

@Injectable({
  providedIn: 'root'
})
export class CountService {
  private _unreadCount$: BehaviourSubject<number> = new BehaviourSubject<number>(0);
  
  get unreadCount$ ():Observable <number> {
    return this._unreadCount$;
  }

  increaseCount(amount:number) {
    this._unreadCount.pipe(take(1)).subscribe((count: number) => {
      this._unreadCount.next(count + amount);
    })

  }

Component A

count$: Subject<number> = new Subject<number>();

getUnreadCount() {
  this.countSvc.unreadCount$.subscribe((count) => {
    this.count$.next(count);
  });
}

increase(count: number) {
  this.countSvc.increaseCount(count);
}

// Template of Component A

<div *ngIf="count$ | async as count">
You have {{count}} notifications
</div>
<button (click)="increase(1)">Increase</button>

This method ensures that your components stay synchronized; just remember to inject the service and subscribe to the unreadCount$ property.

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

Unable to adjust SVG size in React

Can someone explain why resizing an imported svg is not working in this instance? I've tried removing the width and height values on the svg itself, but it didn't solve the issue. const Wrap = styled.div` svg { width: 40px; path { ...

Guide to automatically opening a webview upon launching an ionic application

After encountering difficulties opening a login page from the desktop site with webview when my ionic app launches, I decided to create a separate page named login-check.page. On this page, I included a button that successfully opens the desktop login page ...

Automatically submit a PHP form if the input text box is left blank

I need a way to automatically refresh the data on my page when the textbox is empty. Manually submitting the form works perfectly, but I want it to happen automatically if the textbox is empty. The catch is that I don't want the form to submit while t ...

Discovering the process of mapping transitions in MUI

I'm struggling with mapping my products in mui and placing each one in Grow. However, I keep getting this error message: "Warning: Failed prop type: Invalid prop children of type array supplied to ForwardRef(Grow), expect a single ReactElement". Can a ...

Many mistakes encountered while trying to import web3 into app.js

Encountered 9 errors while trying to import web3 into App.js import React from "react"; import Web3 from "web3"; function App() { return ( <div className="App"> <h1>TEST APP</h1> </div> ...

Toggle Submenu Visibility with a Click

One section of my code is located in sidebar.component.html : <ul class="nav"> <li routerLinkActive="active" *ngFor="let menuItem of menuItems" class="{{menuItem.class}} nav-item"> &l ...

Attempting to display an HTML image utilizing data storage

I'm currently working on building a database for animals at an animal shelter. I have created tables containing species information and when a user selects a specific species, all available animals are displayed. Now, I want users to be able to click ...

What role does JavaScriptExecutor play within the Selenium framework?

Can you explain the concept of JavaScript Executor in Selenium WebDriver? How is it utilized and what are some practical applications within Selenium WebDriver? Please provide an illustrative example for better understanding. ...

Counting the number of documents inserted in MongoDB using Node.js

Is there a way to determine the count of inserted records without needing to repeatedly call db.collection.count()? Here's my code: exports.save = function(json) { var url = 'mongodb://localhost/apps'; MongoClient.connect(url, func ...

Identify when a user switches tabs within the browser and when they switch applications away from the

I am interested in understanding the behavior of the tab's visibility state when a user switches tabs in a specific browser and when they switch out of the application entirely (switching away from the browser). var visibilityState, activeTab = ( ...

How can I implement a method to configure a 404 HTTP header in Angular 5 when a route is not found?

Is it possible to display a custom 404 header on the current page when there is no route matching my array? If not, could this potentially create SEO issues and have unknown pages indexed by search engines? ...

The promise chain from the ngbModal.open function is being bypassed

I'm currently working on implementing data editing within a component. My task involves checking if any of the data fields have been altered, and if so, prompting a confirmation pop-up to appear. If the user confirms the change, the data will then be ...

Unexpected behavior found in Vue 3 when using Proxy for reactivity in classes

I am facing an issue with a Class that has a proxy-based object. The set() method modifies another property of the same class, and everything runs smoothly when the code is executed in JS/TS. class Form { errors = [] values = {} constructor(value ...

Can someone show me the JavaScript code to split a string at every instance of ' '?

Hey there! I have a question about manipulating strings. Take a look at this example: var string = '"In Another World" "Magic Books"' I want to create an array that contains every name within the [""]. How can I ach ...

AngularJS - Filter out items from ng-repeat that match specific string criteria

After successfully cleaning up an external JSON URL feed by removing unnecessary special characters through a filter in my AngularJS code, I am now faced with the challenge of filtering out specific items from an ng-repeat based on a certain string. angul ...

Replacing an item from an object within an array using JavaScript

After researching extensively on this topic and trying various solutions from SO, I am still unable to achieve the desired outcome. I have developed a shopping basket program where users can add items and make purchases by clicking the 'Buy now' ...

Creating a Javascript object from a predetermined array of keys, with the values starting as null

When working with a JavaScript object, I need to extract an array of keys using Object.keys(). Next, I want to use those keys to create a new object where the values are initialized to null. In Python, a similar task would look like this: list_of_keys = [ ...

The functionality of ko.utils.arrayFilter is malfunctioning

I am attempting to sort out an array by excluding users who are already on a previous list: FullList: Tom, Tim, Jim, Jill UsersList: Tom, Jill With the help of a colleague, I managed to utilize this array filter. However, the issue is that the fil ...

Navigating through JSON object fields within Angular component [Version 11]

Check out this Angular service method that calls a basic REST API: import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Token } from './Token'; import { map } fro ...

Challenges with overwriting TailwindCSS classes within a React component library package

I just released my very first React component on NPM. It's a unique slider with fractions that can be easily dragged. Check it out here: Fractional Range Slider NPM This slider was created using TailwindCSS. During bundling, all the necessary classe ...