Angular: Retrieving static values in a component post assignment

I have a constant array of orders declared in the constants.ts file

       export const ORDERS = [
           {
            'id': 'PROCESSING',
            'displayName': null
           },
           {
            'id': 'SHIPPED',
            'displayName': null
           }
        ];

Within my component, I am assigning values to the 'displayName' property

import { ORDERS } from './constants';
-----------------
--------------
setOrders() {
        ORDERS.forEach((order: any) => {

        if(order.id === 'PROCESSING') {
           order.displayName = 'Processing';
        }

        if(order.id === 'SHIPPED') {
           order.displayName = 'Shipped';
        }

     });
    }

However, when I attempt to retrieve the values of 'displayName' in another function, it returns null, even though I can see the value of 'displayName' within the order object

getOrders() {
        ORDERS.forEach((order: any) => {
                console.log(order); // displayName exists in the object
                console.log(order.displayName); // But here it shows null
        });
    }

Both functions reside in the same component. Can someone please assist me with resolving this issue? Thank you.

Update : Full implementation

getTimePeriod() {
        return Promise.resolve((() => {

            this.orderService.getTimePeriod()
                .subscribe(
                    (data) => {
                        this.orderStatusList = data.configParameters;
                        this.orderStatusList.forEach(
                            (s: any) => {
                                if (s.status === 'PROCESSING') { this.setOrders(s.status, s.name); }

                                if (s.status === 'SHIPPED') { this.setOrders((s.status, s.name); }
                            }
                        );
                    },
                    error => {
                        this.errorMessage = this.orderService.handleError(error);
                    }
                );
                })());
    }

    setOrders(status, name) {
        ORDERS.forEach((order: any) => {
            if (order.id === status) {
                order.displayName = name;
            }
        });
    }

     getOrders() {
        return Promise.resolve((() => {

        ORDERS.forEach((order: any) => {
            const { displayName } = order;

            console.log(order); // displayName exists in order
            console.log(displayName); // Null

            this.orderService.getOrdersByDisplayName(buildQuery(null, displayName, null, null))
                .subscribe(
                    (data) => {
                        this.ordersWidgetInfo.push({

                            ...order,
                            ...data,
                            number: data.orders && data.orders.length,
                        });
                    },
                    error => {
                        console.log(`error for ${orderType} : ${error}`);
                    }
                );
        }
        );
        })());
    }

Answer №1

If a bug like this were to arise (aside from incorrect code), it would likely be due to an incorrect order of execution.

However, upon testing your code, it appears to be functioning properly. Check out the example on JSFiddle.

Based on this, it seems that the issue you are facing is probably caused by getOrders being called before setOrders, resulting in null values. To resolve this, ensure that you call setOrders before getOrders.

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

Angular 7: struggling to locate the type declaration file

Everything seemed to be working fine with my project yesterday, but today I ran into an issue right after installing the ngx-pagination module: ERROR in src/app/views/dashboard/step1/step1.component.ts(1,23): error TS2688: Cannot find type definition ...

Discovering if a page can be scrolled in Angular

Hey there, I recently started working with Angular and created an app using the angular material stepper. The issue I'm facing is that some of the steps have longer content, causing the page to become scrollable. I am now trying to find a way to deter ...

Angular version 12 (node:3224) UnhandledPromiseRejectionWarning: Issue encountered with mapping:

Trying to generate the translation file in my Angular project using the command ng extract-i18n --output-path src/translate, I encountered this error message: \ Generating browser application bundles (phase: building)...(node:3224) UnhandledPromiseRej ...

What is the best way to ensure the hamburger menu stays perfectly centered?

My menu is currently aligned to the right and scrolls with the user profile. I want the menu to always be centered and the profile to stay on the right side. I am working with Angular 12 and Bootstrap 5 for this project. Here is the code I have been usin ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...

Error encountered in Jest when trying to use next/font/local: TypeError - (0, _local.default) is not a function

Currently, I am in the process of developing a UI library utilizing MUI, React, and TypeScript within Nx as the build system. To ensure smooth functionality, Jest is being used for testing purposes. However, I recently encountered an issue while attempting ...

What is the best way to extract the inner text from an element within a QueryList<T>?

function addGoatToVaccinationGroup(goatObject: {earTag:string, id:number}){ for (let i = 0; i < this.vaccineQueue.length; i++){ if (this.vaccineQueue[i].earTag === goatObject.earTag){ this.vaccineQueue.splice(i, 1); ...

Passing a custom data type from a parent component to a child component in React

I'm currently working on developing a unique abstract table component that utilizes the MatTable component. This abstract table will serve as a child element, and my goal is to pass a custom interface (which functions like a type) from the parent to t ...

Strategies for Maintaining User Logins

As I test an Ionic2 application on my Android phone, I am faced with the challenge of maintaining user login within the app. The issue is that each time I close the app, I am prompted to log in again. Is there a way for users to stay logged in until they ...

Issue with separatorKeys functionality in ng2-tag-input

I've been experimenting with the ng2-tag-input module using a simple configuration: import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'search-form', template: `<tag-input [( ...

Struggling to make even the most basic example work with TypeScript and npm modules

After stumbling upon this repository that made using npm modules within a Typescript program look easy, I decided to give it a try by forking it and making some changes. My goal was to add another package to get a better understanding of the process. So, I ...

The specified function 'isFakeTouchstartFromScreenReader' could not be located within the '@angular/cdk/a11y' library

I encountered the following errors unexpectedly while working on my Angular 11 project: Error: ./node_modules/@angular/material/fesm2015/core.js 1091:45-77 "export 'isFakeTouchstartFromScreenReader' was not found in '@angular/cdk/a11y&a ...

The ng-select dropdown is experiencing issues on the user interface following an update to the newest versions of Angular 6

Recently, I made the transition of my application from Angular 5 to Angular 6. As part of the update process, I also upgraded ng-select to version 2.4.2, the latest one available on npm/GitHub. However, after the upgrade, the dropdown functionality seems ...

Creating a component with the name "c-name" is not possible because the specified module does not exist

Current working directory /src/app Directory of app.module.ts /src/app/app.module.ts Adding a new component to this directory catalog/single/configurator/[new component here] Attempt #1 to add a component ng g c catalog/single/configurator/details-popo ...

Is there a way to carry out tests on keydown events within Jasmine by specifying the keyCode within an Angular2+

I am working on a project where I need to trigger keydown events on an <input> field. Tools Used Karma v1.7.1 as the test runner Tests running on Chrome browser Using Angular 5 framework Any insights on how I can achieve this? ...

What is the process in Typescript for importing JSON files and dynamically searching for values based on keys?

When working with typescript 3.0.3, I encountered an issue while importing a json file in the following manner: import postalCodes from '../PostalCodes.json'; The json file has the structure shown below: { "555": { "code": 555, "city": "Sc ...

Which packages will be included once ng eject is executed?

After executing the ng eject command, I observed the following messages displayed in the console. The last line indicates that packages have been added as a result of running the command. What specific packages are included when we run ng eject? For refe ...

What is the best way to incorporate master/detail components without relying on hierarchical routes?

I need to combine the following elements. An index page with the route /items (plural). This page should be scrollable. When clicking on individual items, I want to display a detail page with the route /item/:id (singular). The detail page should have a ...

Error: The module '@angular/localize/init' could not be located within the specified directory '/usr/src/app/src'

After upgrading from Angular 8 to 9, I added the @angular/localize package. In my polyfill.ts file, I included the following import: import '@angular/localize/init'; When I compile and run my app locally in a browser, everything works fine. How ...

What is the best way to retrieve information from multiple pages of my REST API?

Recently, I integrated a search engine into my application and now I need to gather all the data available for a particular resource, such as all the posts made by a user. The response I receive from my API looks something like this: { "count": 2, ...