Encountered an error while trying to access a property in an array from a JSON

Why am I continuously receiving undefined error messages and how can I prevent them when attempting to read json data?

Currently, I am delving into Angular and embroiled in a project that involves externally sourced json. Here's a snippet of the json provided. The crucial data lies within the included array:

{jsonapi: {…}, data: {…}, included: Array(2), links: {…}}
jsonapi: {version: "1.0", meta: {…}}
data: {type: "node--quiz", id: "31f020f7-34d9-4b9a-bd2b-0d567eb285dc", attributes: {…}, links: {…}}
included: Array(2)
    0: {type: "node--question", id: "afe7137a-2af1-4cb5-92da-879c495c0070", attributes: {…}, links: {…}}
    1:
    type: "node--question"
    id: "79c06ac9-5995-409f-b84c-4d8a9711d0a9"
    attributes: {title: "Question 1", body: {…}, field_options: "{
    ↵   "1":{
    ↵      "type":"select",
    ↵      "option…   ],
    ↵      "answer":"methamphetamines"
    ↵   }
    ↵}", field_processed: "s:390:"<p>The genius chemist {"type":"select","opt…etamines"} in the Breaking Bad tv series.</p>
    ↵";"}
links: {self: {…}}
__proto__: Object
length: 2
__proto__: Array(0)
links: {self: {…}}
__proto__: Object

This is a sample of my app.component.html:

<mat-toolbar  color="primary">
  <mat-toolbar-row>
  <span>{{ title }}</span>
  </mat-toolbar-row>
  </mat-toolbar>
  <main>
    <mat-card *ngFor="let question of questions.included">
      <mat-card-header>
        <mat-card-title> {{ question.attributes.title }} </mat-card-title>
      </mat-card-header>
      <mat-card-content>
          {{ question.attributes.body.value }}
      </mat-card-content>
      <mat-card-actions>
        TESTING: body content
      </mat-card-actions>
    </mat-card>
  </main>

However, during execution of *ngFor, I encounter the following error in my browser console:

ERROR TypeError: Cannot read property 'included' of undefined
.

Answer №1

While the information is available, it must be present upon form initialization. This can be managed using a straightforward safe navigation operator in the following manner:

 <mat-card *ngFor="let query of queries?.selected">

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

Strategies for resolving a mix of different data types within a single parameter

Here, I am setting up the options params to accept a value that can either be a single string or another object like options?: string[] | IServiceDetail[] | IServiceAccordion[]; However, when attempting to map these objects, an error is encountered: Prope ...

Steer clear of creating new instances within loops in Angular

I am facing an issue with a bug in my code related to the green software scanning of casts. public addFilesToQueue(files: FileList | any): void { const addedFiles: AttachmentItem[] = []; for (let iFileId = 0; iFileId < files.length; ...

Matching packages with mismatched @types in Webpack 2: A comprehensive guide

Having trouble implementing SoundJS (from the createJS framework) in my TypeScript project using webpack 2. In my vendors.ts file, I have the following import: import "soundjs"; Among other successful imports. The @types definitions installed via npm a ...

Is it possible to use the Optimistic Hook with boolean values?

I am facing an issue with a switch component where the checked value is updated only after refetching the data when the user is changed to an admin status. Currently, there is a delay when clicking the switch as it takes time to load and then updates. It ...

Tips for removing a row from a table in Angular4, where there is a delete button located in every row

Component <tr *ngFor="let item of items; let i = index"> <th>{{ i + 1 }}</th> <th>{{ item.id }}</th> <td>{{ item.title }}</td> <th><button (click)="deleteItem()">Edit</button>< ...

Tips for exporting a module from a parent module to a child module

In my HomeModule, I included imports for SharedModule with Angular Material and ToolbarModule. I am wondering how I can import SharedModule only once in HomeModule and have it accessible to all child modules that require it. Here is the code snippet: @NgM ...

Issue with Angular 12 SSR: Translation file paths are not being properly retrieved

In my Angular project, I have a file located at src->app->lang-translate->lang-translate.module.ts that is trying to access files from other locations as shown below: {prefix: "../../assets/translate/Pages/header/", suffix: ".json"}, {prefix: "../ ...

What is the best way to utilize ngForTemplate for wrapping a template?

Using the ngForTemplate in a ListView component for custom templates has proven to be challenging. Modified list-view.component.html: <div class="list-view"> <template ngFor [ngForOf]="items" [ngForTemplate]="template"> </template& ...

Leveraging the Cache-Control header in react-query for optimal data caching

Is it possible for the react-query library to consider the Cache-Control header sent by the server? I am interested in dynamically setting the staleTime based on server instructions regarding cache duration. While reviewing the documentation, I didn&apos ...

Issue with mssql.connect await causing timeout in Jest

Testing some functionality in a nextjs Typescript project that needs to interact with the database directly, not relying on mocked sql query results. But encountering issues with it actually writing to the database. A brief example of the problem: /* @/li ...

Angular 2 reusable component libraries: A deep dive into themes and styles

Unique Issue I am faced with the challenge of customizing Angular components to align with the style requirements of individual client projects. The reusable components are stored in a separate project and packaged using npm. The package is then uploaded ...

Is there a problem with Angular2 using TypeScript?

Currently, I am in the process of setting up my machine for Angular development by following the guidelines provided on https://angular.io/docs/ts/latest/quickstart.html As I proceeded to run "npm start" to launch my site, I encountered an issue with the ...

Error TS2339 occurs when attempting to migrate to TypeScript due to the absence of the 'PropTypes' property on the 'React' type

Currently in the process of converting a javascript/react project to a typescript/react/redux project. Encountering an issue with this particular file: import React from 'react'; import GoldenLayout from 'golden-layout'; import {Provi ...

Exploring ways to list interface keys in order to create a new interface where the value is determined by the corresponding key

How can we iterate through interface keys to create a new interface where the value is dependent on the key? type IParse<T> = { [K in keyof T as K extends string ? K : never]: string // How can we specify that if K === 'a', the type sho ...

Angular 2: Despite changes in property, ElementRef.nativeElement.offSetwidth consistently returns the same value

Recently, I encountered an HTML element that caught my attention: <h1 [style.font-size.em]="mysize" id="title-text" #titleText>{{ screenInfo.title }}</h1> This particular element piqued my curiosity because the variable "mysize" controls the ...

"Error encountered: Unable to resolve dependency tree" message appears when attempting to run npm install

Encountering dependency errors while trying to execute the npm install command for my Angular application. As a newcomer to TypeScript and Angular, I'm unsure of the next steps to take. Any suggestions? Attempted solutions include clearing the npm ca ...

Expanding material UI theme choices through module augmentation is currently ineffective with TypeText

For those experiencing the issue, a codesandbox has been provided for convenience. Click here to access the codesandbox. Curiously, the TypeText feature is not functioning properly while the SimplePaletteColorOptions is working as expected. Despite being ...

Getting a "module not found" error in Next.js while trying to import a TypeScript

Check out this code snippet: // lib/customFunction.ts export function customFunction() { console.log("customFunction"); } // pages/homepage.tsx import { GetServerSideProps } from "next"; // works import { exampleFunction } from "../lib/exampleFile.js" ...

Tips for preserving user information after logging in with firebase authentication

Currently, I have implemented Firebase Authentication in my Angular application to enable users to log in. Here is the login() function within my AuthService: login(email: string, password: string) { return from(firebase.auth().signInWithEmailAndPassw ...

What is the functionality of the init function?

Ever wondered why console.log("init2"); is printed before console.log("init1");? Also, have you noticed that when console.log(categories); is inside the subscribe function, it displays the correct array on the console, but outside the subscribe function ...