The Angular variable won't be available until the promise is resolved, which leads to undefined errors when it's

I am fully aware of why my variable is undefined in this scenario.

At the beginning of the page, I declare an object named section with the following instantiation:

section: Section;

Further down in the ngOnInit function, I utilize a promise to retrieve a value from local storage and assign it to the section variable as shown below:

this.storage.get(CERTIFICATE).then(res => {
  this.certificate = JSON.parse(res);

  this.storage.get(SECTION).then(uuid => {
    this.certificate.sections.forEach(section => {
      if (section.uuid !== uuid) {
        return;
      }

      this.section = section;
    });
  });
});

This implementation works flawlessly. I then make use of this section variable in sections.page.html like so:

<app-section [section]="section"></app-section>

However, upon initial page load, I encounter a 'section is undefined' error. It resolves promptly once the promise returns.

To handle this error, I attempted initializing the section variable with:

section: Section = new Section();

Unfortunately, this approach didn't resolve the issue.

The structure of the Section model is as follows:

import {Question} from './Question';

export class Section {
  id: number;
  uuid: string;
  title: string;
  questions: Question[];
}

Could the absence of a 'constructor' be causing this error? Is there any alternative method to prevent this error?

ERROR TypeError: "_co.section is undefined"

Answer №1

Your iteration loop serves as a form of filtration. An alternate approach could involve employing the following code snippet.

this.storage.fetch(CERTIFICATE).then(result => {
  this.certificateObject = JSON.parse(result);

  this.storage.retrieve(SECTION).then(id => {
    this.sectionDetail = this.certificateObject.sections.filter(partition => partition.id === id);
  });
});

Answer №2

To prevent encountering this error, utilize the *ngIf directive in the following manner:

Declare a flag variable isDataLoaded = false at the beginning of your code.

Then, incorporate this variable into your ngOnint function like so:

this.storage.get(CERTIFICATE).then(res => { this.certificate = JSON.parse(res);

this.storage.get(SECTION).then(uuid => {
    this.certificate.sections.forEach(section => {
      if (section.uuid !== uuid) {
        return;
      }
      this.isDataLoaded = true;
      this.section = section;
    });
  });
});



<app-section *ngIf="isDataLoaded" [section]="section"></app-section>

Once section.id has a value, it will be rendered in the DOM and you will no longer face an issue with undefined errors.

Answer №3

With the help of a friend, I was able to quickly solve this issue by following their suggested method:

section: Section = new Section();

transformed into

section = new Section();

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

Provide an instance of mockClient for AWS SQSClient in a TypeScript class

I'm currently working on unit testing a piece of code that relies on a constructor with an SQSClient object for interacting with an sqs queue. To write effective unit tests, I need to mock the client so that I can test the code without actually access ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...

Issue with Chakra UI Avatar Background Color Not Displaying

My current project involves developing a project management application that enables users to create profiles and optionally upload profile pictures. I have chosen Chakra Ui as my component library for this project. Throughout the application, users are re ...

I require the ability to identify and capture the ID of the button (touchable opacity) that has been

When trying to delete a selected button by obtaining its specific id, I am facing an issue where after the first execution, the id of the deleted item is retained instead of the newly selected one. I am in need of a solution that allows me to retrieve the ...

It's strange that I can easily access jQuery from the developer console, but for some reason I can't access it from

My script bundle contains jquery along with other elements, but when I try to use it from a component, I encounter an error message saying ERROR ReferenceError: $ is not defined. Strangely, when I type $('body') in the console, it works perfectly ...

Getting environment variable from JSON file within Angular 4 - a step-by-step guide

I have a file named "appsettings.json" which contains configurations for a specific purpose. I want to include variables from both "environment.ts" and "environment.prod.ts" in this file and access them within the environment files. When I attempt to impo ...

The agm-snazzy-info-window appears at various locations unpredictably

I am currently working on incorporating the following dependencies: "@agm/core": "^1.0.0-beta.7", "@agm/snazzy-info-window": "^3.0.0-beta.0", "agm-direction": "^0.8.6", "snazzy-info-window&qu ...

A guide to implementing Typescript Generics in modifier functions

I am searching for a solution to properly enforce strong typing in the following scenario. I believe Typescript Generics might be the way to go here. interface Person { name: string; age: number; } const person: Person = { name: "John", ...

Using the `npm install -g @angular/cli` command will not actually install the Angular CLI

I've set out to create a sample Angular2 web app, starting with the installation of Node.js (v 7.1.0) and NPM (v 3.10.9). However, when I try to install Angular CLI by executing 'NPM install -g @angular/cli' in the system command prompt, I e ...

"Conceal Digits with SweetAlert2's Number Mask

Could you assist me in adding a number mask to an input field in sweetalert2? Here is my code: onClick(btn) { let code2_fa = ''; if (JSON.parse(localStorage.getItem('user')).password.two_factors.is_active) { swal({ ...

Expanding current attributes within @types declarations

I want to enhance the Request object provided by express with additional data stored in the session. I attempted to create my own typings file (d.ts) and wrote this code snippet: import * as express from 'express'; declare module 'express ...

Struggling to develop a version of sequelize-auto. Encounter the error message: Unable to locate module './lib/auto' while attempting to execute a command within my project

I'm seeking forgiveness for my lack of experience in TypeScript. I must apologize in advance as I am unfamiliar with Sequelize-auto and need to replace repository and project names in code examples. My goal is to create a fork of Sequelize-auto to cu ...

how to assign a default value for a drop-down menu in Angular 6

How can I set a default value in my dropdown in Angular? <div class="form-group"> <select id="interfaceType" (ngModelChange)="onChange($event)" [(ngModel)]="interfacengmodel" #interfaceType="ngModel" name="interfaceType" class="form-cont ...

JavaScript and Angular are used to define class level variables

Hello, I'm currently diving into Angular and have encountered an issue with a class level variable called moratoriumID in my component. I have a method that makes a POST request and assigns the returned number to moratoriumID. Everything seems to work ...

What is the best way to find information in a multi-page table?

I've implemented a table with pagination and search functionality to look up data within the table. However, currently the search only works within the current page of the table rather than searching the entire dataset. Is there a way to modify the se ...

Lately, I've run into some challenges while trying to set up a category filter for an online store being developed with NodeJs and Angular

When examining the code snippets below, it appears that the filter functions are not functioning as expected. Component HTML: <div class="products-page"> <div class="grid"> <div class="col-3"> <h4 ...

Is there a way to convert a JavaScript object to a class while eliminating unnecessary properties?

In my current project, I am using Typescript with ExpressJS to build APIs. Let's say I have a typescript User model defined as follows: class UserModel { id: number; email: string; password: string; name: string; dob: Date; ge ...

The TypeScript error is causing issues in the Express router file

Here is the structure of my module: import * as express from 'express'; let router = express.Router(); router.post('/foo', function(req,res,next){ // ... }); export = router; However, I'm encountering the following error: ...

Customizing HttpErrorResponse object properties in Angular

I am new to working with Angular (8) and have been developing a frontend SPA that interacts with a Node Express backend API through http calls using the HttpClient module. In the API response, I can define an Http response status along with an additional J ...

The SourceMap in DevTools encountered a parsing error with the message: "chrome-extension

It's been about a week since I first noticed warning messages appearing in my Google Chrome console. https://i.sstatic.net/Aurgz.png Clearing the cache hasn't made a difference; the messages only vanish when in incognito mode. Any suggestio ...