Implementing Global Value Assignment Post Angular Service Subscription

Is there a way to globally assign a value outside of a method within my app component?

This is how my service is structured:

import { NumberInput } from '@angular/cdk/coercion';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Candidato } from "../interfaces/candidato";
import { Cuestionario } from '../interfaces/cuestionario';
import { Respuesta } from '../interfaces/Respuesta';
import { Verdaderos } from '../interfaces/verdaderos';
@Injectable({
  providedIn: 'root'
})
export class CandidateService {

  url="http://localhost:3000/api"

  constructor(private http:HttpClient) { }

  // Methods go here...

The interface "Verdaderos" is defined like this:

export interface Verdaderos{
    Pregunta: number;
}

After retrieving data from the service, an array object containing IDs related to specific responses needs to be counted for sorting purposes. However, the issue I'm facing is with assigning these values to global variables in order to plot them using ngx-charts.

Here is part of the method attempting to count the responses:

// Method logic goes here...

      this.N = countN2;
      this.M = countM2;
      this.P = countP2
    })
  }

Despite successfully printing the desired values via console, I haven't succeeded in assigning them to the global variable needed for plotting using ngx-charts.

The HTML structure required for rendering a pie chart looks like this:

<div class="wrapperuser">
    <div class="container-sm grafico">
        <ngx-charts-pie-chart
        [view]="view"
        [results]="single"
        [gradient]="gradient"
        [legend]="showLegend"
        [labels]="showLabels"
        [doughnut]="isDoughnut">
        </ngx-charts-pie-chart>
    </div>
</div>

Answer №1

One approach is to utilize the pipeable operator map to convert the stream into the required data and employ the async pipe operator in the template. This handles both subscribing and unsubscribing.

single$: Observable<ISingleInterface> = of()

ngOnInit() {
    this.single$ = this.Persona.getCuestionarioRespuestas(ID).pipe(
        map((data: Verdaderos[]) => {
            // calculate `single` as in question
            return single;
        }),
        // the following may be required depending on if ngx-charts needs this
        // startWith(defaultSingleValue)
    );
}
<div class="wrapperuser">
    <div class="container-sm grafico">
        <ngx-charts-pie-chart
        [view]="view"
        [results]="single$ | async" <---------------- async pipe subscribes and passes value
        [gradient]="gradient"
        [legend]="showLegend"
        [labels]="showLabels"
        [doughnut]="isDoughnut">
        </ngx-charts-pie-chart>
    </div>
</div>

If you don't include a default via startWith, single$ | async will initially pass null and then the data will be pass to the component. You may want to guard fully against this with a wrapping

<div *ngIf="(single$ | async) as single">

An alternative is to manually subscribe within the subscribe assign to variable on the component this.single = // calc but the same thing will happen. It'll begin with an an initial value that updates once the data is received.

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

Is it necessary to 'type assert' the retrieved data in Axios if I have already specified the return type in the function declaration?

Consider the code snippet below: import axios from 'axios' async function fetchAPI<T>(path: string, data: any): Promise<T> { return (await axios.get(path, data)).data as T } async function getSomething(): Promise<SomeType> { ...

What are some ways to detect TypeScript type errors in the data of a Vue component?

Recently, I delved into Typescript development using Nuxt-ts and Vue 2. My goal was to steer clear of class-style components so I opted for the following approach. I created my Interfaces in a folder named /types. Whenever I needed to declare a type in a ...

Data has not been loaded into the Angular NGX Datatable

As a beginner in Angular, I am struggling to set data from the module. ngOnInit() { this.populate(); } public populate() { this.productService.getAllProduct('6f453f89-274d-4462-9e4b-c42ae60344e4').subscribe(prod => { this. ...

Tips for attaching to a library function (such as Golden Layout) and invoking extra functionalities

I am currently utilizing a library named Golden Layout that includes a function called destroy, which closes all application windows on window close or refresh. My requirement is to enhance the functionality of the destroy function by also removing all lo ...

Encountered an issue in React and Typescript where the argument type is not compatible with the parameter type 'EventListenerOrEventListenerObject'

One challenge I am facing is integrating Typescript into my React project: componentDidMount() { document.addEventListener('mousemove', this.handleMouseMove); } private handleMouseMove = (e: React.MouseEvent<HTMLElement>) => { appS ...

How can I decrypt a JWT token using Angular?

One of my current tasks involves decoding a jwt token that is provided by the API during the login process. Can anyone provide guidance on how to decode a jwt token in an Angular application? ...

Ways to retrieve data from response instead of subscription JSON in Angular 2/4

My Service : retrieveData(url,request) { return this.http.post(this.apiUrl+url,request).subscribe( (response) => {return response.json()} ); } My Component : ngOnInit() { this.data = this.dataService.retrieveData(&apos ...

Applying ngClass to handle positive and negative numbers and adjust color in Ionic/Capacitor

I have data from my API that includes price and percentage data. I want to display negative numbers in red, and zero or positive numbers in green. After exploring Angular documentation, I found that ngStyle and ngClass can be used for this purpose. I chose ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'e ...

What is the significance of using the @Input decorator on a component property in Angular?

Within this particular component, I discovered the @Input decorator connected to the variable. @Input() description: string; The variable "description" is then utilized in the HTML as an interpolation. <div>{{description}}</div> This prompt ...

When using Google Maps, be sure to load it carefully as it may appear gray on the second attempt

After developing an Ionic 2 / Angular 2 App with integrated Google Maps, I encountered a problem. The second time the Google Maps loaded, it appeared completely gray. Despite trying various solutions found online such as triggering 'resize' event ...

How can I retrieve the row index in an Angular Mat-Table that has expandable content?

Having a mat-table with expandable content on a page, I am seeking a solution to record the row number of the table when clicked. While I successfully achieved this with a regular table in the HTML file using: <tr mat-row *matRowDef="let row; columns: ...

Transferring data between unrelated components

I am facing an issue where I am unable to pass a value from the Tabs component to the Task component. To address this, I have created a separate data service. The value in the Tabs component is obtained as a parameter from another component. However, when ...

Leveraging AngularJS services within an Angular service

I am currently in the process of transitioning my AngularJS application to Angular. To facilitate this transition, I plan to create a hybrid application that combines both frameworks until the conversion is complete. However, I have encountered an issue wi ...

Improper application of Angular bindings in Chrome when navigating to a page using the browser's back button

Have you encountered this issue before? I have a few textboxes generated within an ngFor loop: <tr *ngFor="let tableRow of lineItems; trackBy:trackByIndex; let rowIndex = index; "> <td class="psavingsSmallerGridCell"><input c ...

Issue with updating Angular list reference when deleting an item

My current task involves implementing a feature that displays selected items from a hierarchical structure on the right side. slice.component.ts : import { Component, Input, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core&a ...

The theming feature in Angular 5 with Bootstrap 4 and Bootswatch seems to be malfunctioning

Having trouble implementing bootswatch themes with angular 5 and bootstrap 4? I've added the following to styles.scss: @import "~bootswatch/dist/cerulean/variables"; @import "~bootstrap/scss/bootstrap"; @import "~bootswatch/dist/cerulean/ ...

Encountering an error while implementing a Typescript addEventListener for keydown events

Struggling with adding and removing event listeners to HTML elements capable of focus, such as buttons. encountering a typescript error specifically related to the lines of code responsible for adding and removing the event listener: focusableElements.fo ...

Attempting to send numerous identifiers in an API request

I encountered a problem while working on a function in Angular that involves pulling data from an API. My goal is to enhance a current segment to accommodate multiple IDs, but I face difficulties when attempting to retrieve more than one ID for the API que ...

The ESlint extension in VScode encountered compatibility issues on the MacBook Pro 2021 powered by the Apple M1 Pro chip

After using eslint in vscode on Apple M1 Pro chips, I encountered an issue. I was able to execute eslint via the command line without any problems: > eslint app.js /playground/nodejs/eslint-demo/app.js 1:7 error 'a' is assigned a value ...