What is the process of using observables in Angular to retrieve a number or variable?

While working on an angular service that calls an API and processes a large amount of data, I encountered an issue. I was trying to count the occurrences of each type in the data and send back that count along with the data itself. However, I found that when I tried to save this count as a public variable within the service, it returned undefined when accessed from another component.

I suspect that this is happening because the variable is being accessed before the observable is subscribed to, but I'm unsure how to resolve this issue.

In the code snippet below, you can see that I am trying to use _counts to store the frequency of each type, which works well within the getPciInfo method. However, when I try to access it from outside, it returns undefined (I need to pass this count to a different component).

Any help or advice on how to solve this problem would be greatly appreciated.

public _counts: any;

getPciInfo(): Observable <Ipcidata[]> {
    return this.httpClient.get<Ipcidata[]>('http://dr0-hlp-07/api/PCIMachines')
      .pipe(
              map(results => {

                const sorted = results.sort((a, b) => {
                      const updateDateA = Date.parse(this.datepipe.transform(a.UpdatedDate, 'MM-dd-yyyy'));
                      const carda = determineCardType(a, this.dateMinusMonth, this.dateMinusTwoWeeks)
                      const cardb = determineCardType(b, this.dateMinusMonth, this.dateMinusTwoWeeks)

                      return cardb - carda
                });

                this._counts = sorted.reduce((acc, cur)=>{
                  const cardType = determineCardType(cur, this.dateMinusMonth, this.dateMinusTwoWeeks)

                  switch (cardType) {
                    case 1:
                      acc.green += 1;
                      break;
                    case 2:
                      acc.yellow += 1;
                      break;
                    case 3:
                      acc.red += 1;
                      break;
                  }
                  return acc;
                }, {
                  red: 0,
                  green: 0,
                  yellow: 0
                });
                console.log(this._counts)
                console.log(this._counts.red)

          return sorted;
          }


Answer №1

If you need to return the count, use this code snippet:

return ({sorted, counts: _counts});

To easily share the count across components within this service, you can implement a subject like so:

private countsSource = new Subject();
private counts = this.countsSource.asObservable();

getPciInfo(): Observable <Ipcidata[]> {
    return this.httpClient.get<Ipcidata[]>('http://dr0-hlp-07/api/PCIMachines')
      .pipe(
              map(results => {
                 ....
                 const counts = ...
                 this.countsSource.next(counts)
              });
}

getCounts(): Observable<CountData> {
     return this.counts;
}

In any component, you can consume this information just like any other function:

this.myService.getCounts().subscribe(counts => console.log(counts));

If you want the counts to be sent to new Subscriptions, consider using BehaviorSubject or ReplaySubject.

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

Sharing data from AJAX calls in Vue using vue-resource

After using Vue resource, I'm attempting to create an AJAX call that is based on the data received from a prior AJAX call. I have successfully bound the data fetched from /me to the userDetails prop. However, when trying to pass userDetails.id into t ...

Learn how to connect a Firebase account that was created using a phone number

✅ I have successfully implemented the feature that allows users to update their profile with a mobile number using verifyPhoneNumber and update currentUser.updatePhoneNumber ❌ However, a problem arises when a new user attempts to sign in with a phone ...

Displaying a loading spinner image as PHP script runs

Hey there! I've been experimenting with using a script to show a loading bar while my PHP code is running. I followed the instructions on this website, but even after following the exact steps, my loading bar still isn't showing up. Any suggestio ...

Javascript is failing to execute promises in sequence

Currently, I am facing an issue with the execution of the code below using promises. The problem lies in the fact that the promise is not executing sequentially; it does not wait for the first block to finish before moving on to the next block. Here is th ...

When moving from Babel version 5.8.35 to 6.0.0, be prepared for app.js to throw a SyntaxError and encounter an unexpected token during compilation

Currently, I am in the process of enhancing my ReactJS components using webpack. However, I have encountered a hurdle while trying to transition from babel version 5 to 6. Upon attempting the upgrade, it resulted in a stack trace error within my app.js cl ...

Setting up the initial 3 parameters in a v-for loop

What is the best way to begin a v-for loop? For instance, we have an array named "array" with the following values: array = [dog, cat, e, f, g]; I am interested in using a v-for loop that will start looping through and only consider the first 3 values. ...

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...

Manipulating DOM elements using JavaScript Vanilla with the Jquery <<S.fn.init [selector]>> framework

I have a project where I need to switch the logic written in jQuery to vanilla JavaScript. Here is an overview of my code: I am using the keydown event on an input element to trigger a function that searches an API based on the input value. var selectedU ...

I have tried to install Angular Animations but have encountered difficulty importing it into my project

I attempted to incorporate Animations into my project. C:\gtaui>npm install @angular/animations --save <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04637065716d44342a342a34">[email protected]</a> C:&bso ...

When utilizing multer for handling multipart data, hasOwnProperty appears to become undefined

Below is the code snippet I am currently working with: var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var multer = require('multer'); var user = requir ...

Discover the method for accessing a CSS Variable declared within the `:root` selector from within a nested React functional component

Motivation My main aim is to establish CSS as the primary source for color definitions. I am hesitant to duplicate these values into JavaScript variables as it would require updating code in two separate locations if any changes were made to a specific co ...

Having trouble getting the webpage to update after entering information?

My current project involves automating a website using selenium python. I've encountered an issue where manually entering J590 into the target textbox requires clicking or pressing tab to refresh the page, resulting in an available option in a dropdow ...

Utilize a function from a separate JavaScript file by calling it within the $(document).ready(function()

Refer to this post for more information: Click here I attempted to access a function that was defined in another .js file based on the instructions from the post. However, I encountered an issue. Take a look at my code below: sildemenu.js $(document).re ...

Is there a way to retrieve the chosen selection from a select dropdown element using JavaScript?

As someone who is still learning JavaScript, I've come across a particular issue. Within a webpage, there is a select dropdown as shown below: <select id="selTipoRap" class="form-control" th:field="*{tipoRappresentante}&qu ...

How to handle users with disabled Javascript? Considering redirection to alternate sites for users with script disabled?

I've dedicated today to strategizing the best approach for revamping our company's website, taking into consideration that less than 1% of web users have JavaScript disabled. Our management team strongly believes in ensuring that our website rem ...

The KeyConditionExpression is invalid due to the use of multiple attribute names within a single condition

I am trying to query a DynamoDB table using GraphQL TableName: "JobInfo", IndexName: "tableauGSI", KeyConditionExpression: "tableauGSI_Tableau = tableau AND #D BETWEEN :startDate AND :endDate", ExpressionAttributeNames: { "#D": "date" }, ...

What is the best way to transfer a @ContentChild attribute to a fairy tale?

Is there a way to transfer an attribute from a component with a @ContentChild decorator to a story? Below is the code for the container component: @Component({ selector: 'app-header', templateUrl: './header.component.html', style ...

What is the best way to refresh the user interface while executing a lengthy operation in AJAX/Javascript?

With a need to call multiple processes in series using synchronous AJAX calls, I aim to display the status of each long-running process upon completion before proceeding to the next. Below is an excerpt from the code that illustrates this concept: var co ...

angular2 angular-entity directive

I have developed a component that accepts a template: export class TemplateParamComponent implements OnInit { @Input() items: Array<any>; @Input() template: TemplateRef<any>; } Here is the HTML code: <template #defaultTemplate le ...

Is it possible to resolve the error message "Uncaught TypeError: Cannot read property 'node' of undefined" when utilizing d3-tip with npm?

After installing d3": "^3.5.17" and "d3-tip": "^0.7.1" via npm (d3-tip documentation), the following code was added to my index.js file: var d3 = require('d3'); var d3tip = require('d3-tip')(d3); console.log('d3 version', d3. ...