The tally remains stagnant despite modifications being made

I made a modification to the default .NET Core SPA template by adding a menu item in the nav-menu.component.html file like this:

<li [routerLinkActive]='["link-active"]'>
    <a [routerLink]='["/fetch-data"]' (click)='collapse()'>
        <span class='glyphicon glyphicon-th-list'></span> Requests ({{count}})
    </a>
</li>

This displays the count of requests fetched from the server inside the parentheses. I initialized the count in my TypeScript file as follows:

export class NavMenuComponent {

count: number;

constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {

var url = this.baseUrl + "api/request/TheCount/";
this.http.get<number>(url).subscribe(result => {
  this.count = result;
}, error => console.error(error));

}

The TheCount method simply retrieves the count of requests from the server like this:

[HttpGet("TheCount")]
public async Task<IActionResult> TheCount()
{
    var count = await GetRequestsCount();

    return new JsonResult(count, new JsonSerializerSettings()
    {
        Formatting = Formatting.Indented
    });
}

Everything is working correctly and the count is displayed as expected inside the parenthesis. However, the issue arises when a request is deleted from another component, the count variable in the nav-menu.component isn't updated automatically. This means that I have to refresh the site in order to see the updated count again. Is there a way to automatically update the count after changes?

Answer №1

This is just a sample template.

import { Injectable, EventEmitter } from '@angular/core';
                import { BehaviorSubject, Observable } from 'rxjs';
                import { HttpHeaders, HttpClient } from '@angular/common/http';

                @Injectable()
                export class CountService {

        count: number;

          public observalbleCount: BehaviorSubject<number>;


                  constructor(
                    protected httpClient: HttpClient) {
        this.count= 0;
                    this.observalbleCount = new BehaviorSubject<number>(this.count);
                  }

                  getCount(): Observable<number> {

return new Observable((observer) => {

this.httpClient.get<number>(url).subscribe(result => {
                        this.count = result 
                        this.setCount(result);
                        observer.next(result);
                      }, error => console.error(error));
                      });



                  }

                  public setCount(data: number) {
        this.count=data;
                    this.observalbleCount.next(data);
                  }

                }

This is the actual component code.

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

import { CountService } from './';

@Component({
    selector: 'app',
    templateUrl: 'app.component.html'
})

export class NavComponent implements OnDestroy {
    count: number;
    subscription: Subscription;

    constructor(private countService: CountService) {
        // subscribe to home component messages
        this.countService.GetCount().subscribe((data) => {
          this.count = data;
        });
this.subscription = this.countService.observalbleCount.subscribe((data) => {
          this.count = data;
        });
    }

    ngOnDestroy() {
        // unsubscribe to ensure no memory leaks
        this.subscription.unsubscribe();
    }
}

Answer №2

When making changes to the data, ensure that the count is always updated accordingly.

Integrate your code into the service layer.

this.http.get<number>(url).subscribe(result => {
  this.count = result;
}, error => console.error(error));

}

Implement a Subject or BehaviorSubject for a specific variable (count) within the service.

This way, any changes to the data will trigger the service method and update the count.

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

Tips for creating a generic type that is versatile

I came across this helpful solution here After studying it, I saw potential for improvement to make it more versatile. That's when I developed a new, even more universal generic type: export type extractGeneric<Type, Parent> = Type extends Pare ...

Updating a SQL parameter to reference a foreign key

SELECT StaffID, SUM(Treatment.TreatmentPrice) AS TotalStaffRevenue, SUM(Treatment.TreatmentPrice) * ? AS Commission FROM Treatment INNER JOIN Appointment ON Appointment.TreatmentID = Treatment.TreatmentID WHERE AppointmentDate ...

Unable to return to the initial page in Selenium using C#

I recently posted a query about my difficulty in returning to the original page after closing an Iframe modal. I attempted to resolve this issue with the following code: driver.SwitchTo().DefaultContent(); string currentWindow = driver.CurrentWindowHandl ...

Utilizing webpack to implement HTML loaders alongside Angular 2's built-in directives in lowercase

While using html-loader to load my HTML template and file-loader to load images within the template, everything works smoothly in development. However, when I build for production and run the output, a template parse error occurs. The issue seems to stem ...

When submitting the form in Angular using Reactive Forms, the select dropdown may send a null value

Whenever I attempt to submit a reactive form, the selected value from the dropdown is showing as null instead. I am using Angular 12 and have also tried using [ngValue] for the option tag with no success. Below are the HTML, TypeScript component, and modul ...

How to make a dynamic Div tag using ASP.Net

I am working on a Web Application where I have been using multiple div elements to display pop ups. Now, my new requirement is to generate dynamic div containers for these popups, with the content of each div coming directly from the Database. Is there a ...

What are the solutions to resolve this error in C# ASP LINQ?

Just moments ago, this section of my code was running smoothly. However, in a sudden turn of events, I encountered an issue when compiling the project. Here is the snippet of code causing trouble: string Cat = ddlCategoria.SelectedValue; int? Max ...

"Troubleshooting Primeng's p-table filter issue when using an editable FormArray - encountering problems with the

I'm encountering a problem with the filter functionality on primeng p-table when using formarray controls. The filter doesn't seem to work correctly, so I tried registering a custom filter and testing it. However, I found that the value is null f ...

Uh oh! An issue occurred: StaticInjectorError(AppModule)[UserformService -> HttpClient] - There seems

After attempting to incorporate a PrimeNG table into my project, I encountered issues with my build. You can view the broken state of my code at https://github.com/BillyCharter87/Tech-O-Dex-UI/tree/BrokeIt I believe the problem arose when I updated my pac ...

Managing Keyboard Input in React using TypeScript

Hey there! I'm currently working on a method that should automatically insert a specific string into a textbox when a particular key is pressed. The key in question is a non-printable character that may not be visible in most font styles, but can sti ...

What is the method for utilizing enum values as options for a variable's available values?

I'm curious about using enum values in TypeScript to restrict the possible values for a variable. For example, I have an enum named FormType with Create and Update options. Is there a way to ensure that only these enum values are used? enum FormType { ...

a dynamic assortment of serialized arrays in C#

Is it possible to dynamically create a variable number of arrays with specific serialization? For example: for (int i = 0; i < var; i++) { int[] s"i" = new int[var2]; } where "var" and "var2" can be any positive integers. As an outcome, if we set ...

Save the selected date from a date chooser onto a MySQL database

Greetings, I am facing an issue with inserting a date from a JDateChooser into MySQL in a format that MySQL accepts. I am currently using the MVC framework and inserting the data as shown below: This is my driver class I added a jtxfile just to try to us ...

Guide on Building a Node with Neo4jClient in Neo4j Version 2

Previously, under Neo4j v1.9.x, I utilized the code below: private Category CreateNodeCategory(Category cat) { var node = client.Create(cat, new IRelationshipAllowingParticipantNode<Category>[0], new[] { ...

Utilizing Typescript for directive implementation with isolated scope function bindings

I am currently developing a web application using AngularJS and TypeScript for the first time. The challenge I am facing involves a directive that is supposed to trigger a function passed through its isolate scope. In my application, I have a controller r ...

Enabling LinkButton in Asp.net after a delay of 10 seconds: A Step-by-

After clicking on the LinkButton lbUpVoteUndo, I need it to be disabled for a set period of time, such as 10 seconds. I attempted to achieve this using c# code-behind but now I'm curious if there is an alternative method to accomplish the same task. ...

I'm looking to locate the API documentation for AngularJS TypeScript

After transitioning from using AngularJS 1.4 and plain JavaScript to now working with AngularJS 1.5 but utilizing TypeScript, I have found it challenging to find helpful documentation. For instance, when trying to inject services like $q or $timeout into m ...

Maintain the selected list item active using ngFor after it is clicked

I am currently working with Angular and Typescript, and I have the following HTML code snippet. However, I am facing an issue where the items are not staying active after being clicked. <li *ngFor="let permission of tempPermission" class ...

"Encountering an issue with opening a form in a child component from the parent - receiving an error message 'unable to access

Here's the scenario: I am working with a list of companies that each have an array of projects as one of their variables. The desired functionality is to display the list of companies in the parent component/html, and only open a child component to sh ...

Problems encountered when utilizing $in operator in Mikro ORM MongoDB operations

For my project, I'm utilizing mikro orm with MongoDB to handle database operations in TypeScript. So far, it has proven to be the most effective ORM for MongoDB in this language. However, I've encountered type errors when using $in with Object ID ...