What is the reason for the lack of variable assignment within the forEach method in Angular?

I am struggling with assigning a value to the variable "this.qdDias" and returning it. After using subscribe, I am unable to retrieve the value at the end of the method. Despite seeing the value in the console.log(this.qdDias), it becomes undefined when returned.

> obterParametroPrazoMap(nomePrazo: string): number {
>         console.log("Parametro vindo: ", nomePrazo)
>         this.service.obterParametrosgeraisMap().subscribe((data) => {
>             this.listParametrosGerais = data.data;
>             this.listParametrosGerais.forEach((x) =>  (this.listParametrosGerais, x));
>             for (var i = 0; i < this.listParametrosGerais.length; i++) {
>                 console.log("comparado: ", this.listParametrosGerais[i].chavePrimaria.tipoParametro.nomeTipoParametro)
>                 if (this.listParametrosGerais[i].chavePrimaria.tipoParametro.nomeTipoParametro
> === nomePrazo) 
> {   
>                     this.qdDias = this.listParametrosGerais[i].quantidadeDiasPrazo;
>                     console.log(this.qdDias)                    
>                     break
> }
> }
   }                   
);       
return this.qdDias;
     }

Is there a solution to this issue?

Answer №1

return this.qdDias is not within the scope of subscribe. Even if the return statement was inside subscribe(), it would still not work. The issue lies in subscribing to an asynchronous observable

this.service.obterParametrosgeraisMap().subscribe()
while treating it as synchronous.

Is

this.service.obterParametrosgeraisMap()
an observable that requires subscription? If so, it should be
this.service.obterParametrosgeraisMap
.

What does this do?

this.listParametrosGerais.forEach((x) => (this.listParametrosGerais, x));

Why use var? Consider using const or let instead?

This approach might partially work, but you need to determine whether you want to return an observable to extract the value from it or transform it into a promise to maintain the asynchronous pattern. More information can be found here:

    function obterParametroPrazoMap(nomePrazo: string): number {
        console.log('Parameter received: ', nomePrazo);
        let map;
        this.service.obterParametrosgeraisMap.pipe(take(1)).subscribe(data => map = data);

        this.listParametrosGerais = map?.data;
        this.listParametrosGerais.forEach((x) => (this.listParametrosGerais, x));
        for (var i = 0; i < this.listParametrosGerais.length; i++) {
            console.log('compared: ', this.listParametrosGerais[i].primaryKey.parameterType.parameterName);
            if (this.listParametrosGerais[i].primaryKey.parameterType.parameterName === nomePrazo) {
                this.qdDias = this.listParametrosGerais[i].deadlineDays;
                console.log(this.qdDias);
                break;
            }
        }

        return this.qdDias;
    }

Answer №2

This is the solution I came up with:

Promise.resolve(2);
        Promise.all([
           this.service.retrieveGeneralParametersMap()
                .then((list: any) => {
                    this.generalParametersList = list.data;
                })
            ,
 this.service.retrieveSpecificParametersMap()
                .then((list: any) => {
                    this.specificParametersList = list.data;
                })
        ]).then(() => {    
            this.initializeDictionaryVariables();
 });

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

When an action is clicked within a cell of an Angular Material table row, the (click) event for that row is triggered

Is there a way to activate a modal using a button within a mat-table without triggering the row click event? I've come across Angular Material 2 Table Mat Row Click event also called with button click in Mat Cell but implementing $event.stopPropagatio ...

Angular 2 - Ensuring service executes only when boolean condition is met

I am currently dealing with a navigation menu that utilizes the ng2-page-scroll module. When scrolling through the page using hashtag links, I encountered an issue. If I navigate across routes, there is a delay in loading the data. As a result, the servic ...

Utilizing the Pub/Sub architecture to integrate the kafka-node library within Node Js

Utilizing the kafka-node module in my NodeJs Microservise project, I am aiming to implement a Pub/Sub (publisher and subscriber) design pattern within the Functional programming paradigm. producer.js const client = new kafka.KafkaClient({ kafkaHost: ...

What is the best way to determine if a local storage key is not present?

By applying the if condition below, I can determine whether or not the local storage key exists: this.data = localStorage.getItem('education'); if(this.data) { console.log("Exists"); } To check for its non-existence using an if conditi ...

Update the icon in real-time based on the text with Angular 8 and Font Awesome, achieving dynamic changes effortlessly

I need to dynamically change the icon based on the value within a span element. Here is the HTML structure: The version text will only have two possible values: If the value is "Active", then a success icon should be displayed. If the value is "Inactive ...

Using JSON as a variable solely for determining its type and guaranteeing that the import is eliminated during compilation

In my TypeScript backend project with Node as the target runtime, I have a JSON file that is auto-generated within my repository. I use the following code to import the JSON file in order to get the type of the JSON object: import countries from '../g ...

Troubleshooting problem with iPhone X responsiveness

Struggling with responsive issues on iPhone X. Issue is only appearing on actual device. Any tips for fixing this? I'm facing an issue where the website looks good and responsive on all devices in Chrome's responsive view. But when I access it th ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

Angular displays the error message TS2339, stating that the property 'handleError' is not found on the 'HeroService' type

Hey everyone, I know there are already a few questions out there about Typescript compilation errors, but I'm facing a unique challenge that I can't quite figure out. I'm currently working on the Angular Tour of Heroes app and trying to com ...

I am facing an issue with Nestjs where it is unable to resolve my dependency, despite the fact that it is readily available within the

Encountering the following error: Error: Nest is unable to resolve dependencies of the CreateGroupTask (TaskQueueService, GroupsService, ?, GroupNotificationsService, GroupRepository, Logger). Please ensure that the argument dependency at index [2] is avai ...

Input for uncomplicated changing identifier

I am looking to create types for dynamic keys that will be of type number. I have two similar types defined as follows: type UseCalculatePayments = () => { totalPayments: number; aggregate: number; condition: boolean; }; type UseCalculateCommissio ...

Node installation failed due to npm encountering an ETIMEDOUT error

Recently, I've been encountering some obstacles while attempting to install npm on our office's laptop within a specific directory. An error message keeps popping up: npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT np ...

The TypeScript 'object' type

My query regarding the definition of TypeScript's {} type has brought about some confusion. Initially, I believed it represented an "empty object with no properties," but I recently encountered an ESLint rule that prohibits the use of {} type because ...

Several mat-radio-button options chosen within mat-radio-group

`<mat-radio-group [ngClass]="cssForGroup" name="test"> <mat-radio-button *ngFor="let option of options | filter:searchText" class="cssForRow" [value]="option" ...

Failing to reach the nested if statements within a switch case block

Before removing my question, please read this. Despite testing with console.logs, my code does not enter the if statements. I have not come across a similar solution to my issue. In an attempt to address any timing or asynchronous problems, I added a use ...

It appears that Yarn is having trouble properly retrieving all the necessary files for a package

Recently, I encountered a strange issue in our project involving 3 microservices, all using the exceljs library. Two of the microservices successfully download all necessary files for this package through yarn. However, the third microservice is missing ...

What are some ways to enhance Rxjs syntax?

save(): void { combineLatest(this.selectedSorting$, this.selectedFilters$) .pipe( map((data) => { let obj = {}; if (data[0]) { obj['fil ...

Examining interconnected services' dependencies

Looking to test out AService, which has dependencies on BService and CService. The dependency chain looks like this: AService --> BService --> CService The constructor for AService is as follows: constructor( private bService: BService ) {} The ...

Preventing image flickering in SvelteKit: A guide

Upon the initial loading of a website, you may notice that the images tend to flicker or flash when transitioning between them. However, once these images are stored in the browser's cache, subsequent visits to the site will display the images seamles ...

Angular2's service executing http method is limited to just once

I have a service that is responsible for retrieving information from the server. The goal is to execute the request only once and then share the data with every component in the application. Currently, my code looks like this: @Injectable() export class P ...