Having trouble accessing undefined properties? Facing issues with the latest Angular version?

Why am I encountering an error and what steps can be taken to resolve it? Currently using the latest version of Angular.

ERROR TypeError: Cannot read properties of undefined (reading 'id')

Here is the JSON data:

{
"settings": [
    {
        "test": "test",
        "title": "Service 1"
    }
],
"services": [
    {
        "id": "1",
        "title": "Service 1"
    },
    {
        "id": "2",
        "title": "Service 2"
    }
]

}

The code snippet below is from app.component.html:

<p>service id {{ service.id }}</p>

Below is the section of app.component.ts where the issue might lie:

  ngOnInit(): void {
    // Retrieve data
    this.api.getApi()
      .subscribe(res => {
        this.data = res;
        // Get specific service
        this.service = this.data.services.filter((obj: any) => {
          return obj.id === this.id;
        });
      });
  }

Answer №1

Initially, it is important to note that the .filter function will return an array rather than an object. If you have successfully received the data within the service array, you will need to iterate through this array to access the id field as shown below:

<div *ngFor="let s of service">
  {{ s.id }}
</div>

Prior to this implementation, consider using console.log on the service variable to ensure that the data is being retrieved correctly.

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

Utilizing scrapy and python to gather information on attractions from Tripadvisor

Struggling to extract the names and addresses of attractions from TripAdvisor using web scraping. The suspicion is that there might be an issue with how product.css(...) is written (possibly related to jsons?). Seeking guidance on correcting the code in o ...

How to remove the footer on a particular webpage

I am currently using angular version 14. On a specific page, there is a footer visible that I wish to hide. This page pertains to job search, and I would like to remove or conceal the footer specifically from this job search page. The footer has been separ ...

What is the best way to pass a Python string to a JavaScript script?

I attempted to utilize the JSON module for this task, but encountered errors in both my JavaScript script and Firebug. For example, I have a line that looks like this: {"fruit":{"apple":100}} When trying to send this to a JavaScript script called jquery. ...

Import data from JSON using JavaScript

I have a collection of txt files that contain custom content. The file names are stored in a JSON array. { txtFiles: ['./file1.txt', './file2.txt', './file3.txt'] } I am looking to use the require function in JavaScript t ...

What is the correct way to invoke a function from a separate file in typescript?

I am new to typescript and still learning. I have a question regarding calling a function defined in file B from file A. Can someone guide me on how to achieve this? ...

Using Webpack 4 and React Router, when trying to navigate to a sub path,

I'm currently working on setting up a router for my page, but I've encountered a problem. import * as React from 'react'; import {Route, Router, Switch, Redirect} from 'react-router-dom'; import { createBrowserHistory } from ...

There was an error encountered in the Recovery service Vault when attempting to add Policies for SQL Backup

I encountered an issue while setting up backup policies using Azure ARM Template for weekly SQL Backup. Any assistance would be greatly appreciated. It seems that the backupmanagementype for VM is AzureIaasVM, so for SQL it should be "backupManagementType ...

Learn how to dynamically add and remove a CSS class from an element using a scroll event in Angular 7

My goal is to create a navbar that gains a "fixed-top" class during scrolling and removes it when it reaches the top of the page. I've written the following script, but unfortunately, it's not working as expected. import { Component, OnInit, Af ...

Issue detected with XMLHttpRequest - "The requested resource does not have the 'Access-Control-Allow-Origin' header."

Currently, I am working on the frontend development of an application using Angular 2. My focus is on loading an image from a third-party site via XMLHttpRequest. The code I have implemented for this task is as follows: loadFile(fileUrl) { const ...

Add a hyperlink within a button element

I am looking to add a route to my reusable 'button' component in order to navigate to another page. I attempted using the <Link> </Link> tags, but it affected my CSS and caused the 'button' to appear small. The link works if ...

The Angular template is throwing an error stating that c_r1.getCatType is not a valid function

Within my Angular project (version 9.1.0), I have a class structured like this: export class Contract { contractName: string; limit: number; public getCatType(): string{ if(this.limit > 0) return 'p'; return &ap ...

Searching function in material-table does not work properly with pipe symbol

Within my data table, I utilize the @pipe to display name instead of position in the position row... The name is sourced from a separate JSON file... <ng-container matColumnDef="position"> <mat-header-cell *matHeaderCellDef> No. </ma ...

There is an issue with the typings for React.createElement that is causing errors

Is it possible to implement React.createElement with TypeScript successfully? import React from "react"; type Props = { label: string; }; const Three: React.FC<Props> = (props: Props) => { return <div>{props.label}</div&g ...

Navigating Through Angular Components

I have a layout with 3 components arranged like this: <app-header></app-header> <app-body></app-body> <app-footer></app-footer> However, I want to change the positioning of the footer and body as shown below: <app-he ...

Is it possible to establish a specific many-to-many relationship using Prisma?

In the Prisma documentation, it states that the set function can be used to override the value of a relation. const user = await prisma.user.update({ where: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73121f ...

Utilizing External Libraries Added Through <script> Tags in React

My goal is to develop a Facebook Instant HTML5 application in React. Following their Quick Start guide, Facebook requires the installation of their SDK using a script tag: <script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></scrip ...

Creating a new JSON by extracting a specific branch or node from an existing JSON data

I have a Nuki Smartlock and when I make two API calls to the Nuki Bridge, I receive JSON responses. I want to apply the same logic to both responses: When requesting for current states, the JSON looks like this: [{ "deviceType": 0, "nuk ...

Dealing with problems related to types in React and TypeScript createContext

Struggling to pass the todos (initial state) and addNewTodo (methods) using React Context hook and typescript. Despite trying multiple solutions, errors persist. Partial generics do not cause issues in the context component, but I encounter the error Cann ...

What steps are involved in generating a Typescript module definition for a directory containing a babel-plugin-content-transformer?

Currently utilizing the babel-plugin-content-transformer to import a directory containing YAML documents in a React Native/Expo project. The configuration for my babel plugin looks like this: ['content-transformer', { transformers: [{ ...

How to conceal parameters in Angular URL?

Within the modeling-agency component, there is a button that routes to editModelingAgency/{{element.userid}}. Currently, clicking on this button takes the user to a specific route with a link like /base/editModelingAgency/15, but I want to show the link as ...