Encountering issues with Angular2 App when attempting to load simulated data using a Promise causes malfunction

Looking to implement my mocked data loading using a promise, similar to the approach shown in the Angular2 Tutorial found here.

Service (Mock):

import { Injectable } from '@angular/core';
import { ERGEBNISSE } from "./mock-ergebnisse";

@Injectable()
export class ErgebnisMockService {
    getErgebnisse() {
        return Promise.resolve(ERGEBNISSE);
    }
}

Component:

import { Component, OnInit } from '@angular/core';
import { ErgebnisMockService } from "../shared/mocks/ergebnis.mock.service";

@Component({
    moduleId: module.id,
    selector: 'ergebnisse',
    templateUrl: 'ergebnisse.component.html',
    styleUrls: ['ergebnisse.component.css'],
    providers: [ErgebnisMockService]
})
export class ErgebnisseComponent implements OnInit {
    ergebnisse: any;

    constructor(private ergebnisService: ErgebnisMockService) {
    }

    ngOnInit() {
        this.getErgebnisse();
    }

    getErgebnisse() {
        this.ergebnisService.getErgebnisse().then(data => this.ergebnisse = data);
    }

}

Encountering an error in the console:

ORIGINAL EXCEPTION: TypeError: Cannot read property 'Bereich' of undefined
(The 'Bereich' property does exist on the mocked object.)

When I remove the promise and return the mock-object directly, everything works as expected:

getErgebnisseWithoutPromise() {
        return ERGEBNISSE;
    }

Upon logging the resolved Object, it shows the mock-object as expected:

getErgebnisse() {
        this.ergebnisService.getErgebnisse().then(
            data => {
                this.ergebnisse = data;
                console.log(this.ergebnisse);
            }
        );
    }

This returns:

Object {Bereich: Array[3]}
>Bereich:Array[3]
>__proto__:Object`

Any ideas on what could be going wrong here?

Appreciate any assistance!

Answer №1

It's worth noting that your object is loaded asynchronously, even when the promise is resolved immediately. This can lead to issues in your template if you try to access a property like ergebnisse before it's defined:

{{ergebnisse.Bereich}}

To avoid this problem, you should utilize the Elvis operator. In this case, you can use something similar to the following:

{{ergebnisse?.Bereich}}

Jake Archibald succinctly explains the core of your issue:

Once a promise settles, or if it has already settled, it queues a microtask for its reactionary callbacks. This ensures promise callbacks are async even if the promise has already settled.

(source: https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules)

For further reading, check out these links:

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 possible to share screens via socket.io without the need for selecting a screen prompt?

I am looking to select my screen and share it on a socket.io server without any pop-up form the browser using navigator.mediaDevices.getDisplayMedia({ video: true }).then((stream: MediaStream) => { ...

The activation of Angular 2 pipe

I currently have a variety of models in my collection. When it comes to using pipes in the template, I often run into issues. <div class="card-panel" *ngFor="let card of cards | sortByType"> <card-view [card]="card" [autoupdate]="true">< ...

Laravel web socket pusher malfunctioning despite the event being triggered

I've been working on integrating Laravel Websocket for socket connections in my application. Despite following all the steps outlined in the Laravel documentation, I'm encountering issues. The dashboard does not display any active connections, a ...

Building basic objects in TypeScript

My current project involves utilizing an interface for vehicles. export interface Vehicle { IdNumber: number; isNew: boolean; contact: { firstName: string; lastName: string; cellPhoneNumber: number; ...

Using the @Input directive in Angular to bind the disable attribute to a button component

I'm currently in the process of developing a button directive that has the ability to receive a boolean value through the @Input and subsequently bind it to the disabled attribute of the <button> element. Here is a snippet of what I have been w ...

Angular2's hidden feature isn't functioning properly

There is a common suggestion to use *ngIf better than [hidden] but in my scenario, I want to keep the element in the DOM without it being visible. In my component.html file, I have: <article #articleId id="bodyArticle" [hidden]="isClicked"></art ...

Nuxt - asyncData ISSUE: "Variable '$axios' is inferred to have an 'any' type."

Referencing the guidelines provided at Encountering an error logged in console while executing yarn dev: ERROR ERROR in pages/index.vue:51:21 ...

What is the best method for connecting an Angular 2 application with an existing Angular JS app?

I recently created an application using Angular 2 and now I am looking to combine it with an Angular JS app. ...

What is the best way to display two arrays next to each other in an Angular template?

bolded text I am struggling to display two arrays side by side in an angular template. I attempted to use ngFor inside a div and span but the result was not as expected. A=[1,2,3,4] B=[A,B,C,D] Current Outcome using ngFor with div and span : Using Div : ...

What steps can be taken to resolve the issue of receiving the error message "Invalid 'code' in request" from Discord OAuth2?

I'm in the process of developing an authentication application, but I keep encountering the error message Invalid "code" in request when attempting to obtain a refresh token from the code provided by Discord. Below is a snippet of my reques ...

Troubleshooting problem with installing Nebular theme on Angular 14

There was an issue resolving the dependency tree for npm with error code ERESOLVE. While trying to resolve the dependencies for [email protected], it was found that @angular/[email protected] version 14.2.0 is required at the root level, but th ...

Utilizing TypeScript to define React interfaces

How can I effectively utilize two interfaces for the same object? For instance: interface interfaceOne { id: string color: string } interface interfaceTwo { id: string numb: number } I have an Item component that is designed to receive an item ob ...

Using custom elements in both React and Angular is not supported

After successfully creating a custom element in React using reactToWebComponent, I integrated it into a basic HTML file like this: <body> <custom-tag></custom-tag> <script src="http://localhost:3000/static/js/bundle.js&quo ...

The element 'PROGRAM_ID' is not recognized within the 'import @metaplex-foundation/mpl-token-metadata' type

I am currently in the process of creating a token within the Solana network, but I've encountered a particular issue. I have successfully installed @metaplex-foundation/mpl-token-metadata and integrated it into my code; however, an error is persisting ...

Duplicate items within an array were found when receiving Node.js response data in Angular

I'm facing an issue where duplicate elements are being displayed in an Angular table when receiving data from Node.js. The array sent by Node.js contains 2 elements, but somehow it appears as 4 elements in the Angular table. This discrepancy is puzzli ...

Setting up Typescript with React 17 and Tailwind CSS version 2.0

I'm struggling to set up TailwindCSS 2.0 with the create-react-app --template typescript configuration and encountering errors. Even after following the instructions on the official TailwindCSS website for React at https://tailwindcss.com/docs/guides/ ...

There seems to be a malfunction in utilizing promises to manage flow

In an attempt to manage the sequential flow of execution in my code, I am encountering some issues. My goal is to read and update data from my database in the correct order. The function below is where I make calls to the database, with query functions wra ...

When the value remains unchanged, Angular's @Input() value does not get updated

Upon running this program, I initially receive the output as false, 5, 500 since they have been initialized in the child component. However, upon clicking the update button, I am unable to revert to the previous values. Instead of getting true, 10, 1000, I ...

Effective ways to manage extensive forms in Angular 2

I have a complex form in my application. What is the most effective way to collect data from this form and transmit it to the API using Angular 5? ...

Angular 2.0's development of modules and implementation of shadow DOM focuses on supporting a left

My website supports "right to left" languages like Arabic. When the language is Arabic, I add the dir="rtl" attribute to the body tag. This aligns all inline positioned children from the right side, even within custom components. Now, I want a custom styl ...