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

Can Flask convert a JSON Array object into a Python string?

When I receive a JSON-encoded parameter in my Flask server via an HTTP POST from the client application, the JSON object structure seems to be causing some confusion. In this example, I have included only the first 2 entries of the JSON object for simplic ...

How to iteratively process JSON array using JavaScript?

I am currently attempting to iterate through the JSON array provided below: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "<a href="/cdn-cgi/l/email-pro ...

An issue has occurred: The function _co.deleteConsulta is not recognized as a valid function

While following a tutorial on creating a CRUD application using Firestore, I encountered an issue when trying to delete data from Firestore. Every time I attempt to delete a user from my Firestore database, I receive an error stating that ._co.deleteConsul ...

Issues with Webpack bootstrap-loader: Unable to locate './bootstrap-styles' and Unable to locate './bootstrap-scripts'

I am attempting to integrate bootstrap-loader into my angular 2 project. However, during Webpack compilation, I am encountering errors: ERROR in ./~/bootstrap-webpack/index.js Module not found: Error: Can't resolve './bootstrap-styles' in & ...

How to use AJAX to retrieve data from a JSON file hosted on an external URL?

Is it possible to extract data from a JSON file that belongs to an external source such as ABS, a company that provides weather information? The weather data is stored in a JSON File. Why am I unable to access this information and save it? & ...

The FAB button animation is causing delays in the transition process and is not functioning as originally anticipated

I am facing an issue with the FAB button and 3 Icons. The functionality is working fine on click for both show and hide actions, but the transition is too delayed. I want the icons to appear step by step, even though I have adjusted the transition delay se ...

Adding a value to a JSON array using Bash

I have been working on a bash script to parse a URL into its different components. I am currently facing an issue while trying to add an array value to a key within a JSON object. What I've Tried: The URL that I parsed is: https://bar.foo.com/v2020/ ...

Refreshing Angular2 View After Form Submission

Currently, I am in the process of developing a basic CRUD application with Angular2. The application comprises of a table that displays existing records and a form for adding new records. I am seeking guidance on how to update the table to show the new rec ...

Tips for ensuring the page remains functional with the signOut feature even after a refresh

I am facing an issue with my website. On the home page, I have a sign-in and sign-out column. Then, on the user page, there is a sign-up form. When I sign out, it works fine but upon refreshing the page, it still shows as if the user is not signed out. Can ...

Struggling to retrieve a particular value in Angular, but encountering difficulties

I am attempting to retrieve information from my Firestore Collection. Everything works fine when I print the JSON data, but I am encountering issues when trying to display a single value. In order to fetch the data, I have implemented the following code: ...

Highcharts: generating numerous series utilizing JSON dataset

I am struggling to generate a chart with multiple series using JSON data. Although I have successfully created one with a single series, it doesn't look right and the legend is missing. I need guidance on how to rectify this issue. Currently, I only h ...

There has been an unhandled runtime error: [object ProgressEvent] occurring with Next.js/Typescript

Exploring the world of nextJS and typescript is new to me. I am currently working on creating a simple blog using nextJS/typescript with a sanity CMS backend. Everything seems to be running smoothly during development, but then I encounter this Unhandled R ...

Take a flat array and transform it into a two-dimensional array where each row contains associative elements

I am working with an array structure similar to this: [ 123456 => 'John Doe' 654321 => 'Doe John' ] My goal is to transform the numeric keys (e.g. 123456 and 654321) into sequential indexes (0, 1, 2, 3,...) and store them ...

Removing an element from a dynamic dictionary in Python removes it from the entire dictionary, rather than just a specific key

Currently, I am developing a dynamic dictionary where I encountered an issue. I need to remove an element from a specific array within the dictionary without affecting the rest of the data. The problem arises when attempting to remove an item only from a p ...

Issue with Angular2/4 Module: Unable to locate 'three' in the application directory

As a newcomer to Angular and TypeScript, I am encountering difficulties when trying to import the @types/three npm package. I have created a new Angular project and attempted to use the three package, but I keep receiving the following error: Module not f ...

How to display JSON images in an Android listview

I'm facing difficulty in loading images from a JSON file to the listview on my Android app Although I know that I need to use BitmapFactory.decodeStream, I am unsure about how to proceed with the implementation Below are the details of my adapter an ...

Capture and store the current ionic toggle status in real-time to send to the database

I have a list of names from the database that I need to display. Each name should have a toggle button associated with it, and when toggled, the value should be posted back to the database. How can I achieve this functionality in an Ionic application while ...

A secure way to perform a deep update on any type, even if it is completely different from the original

Is there a method to eliminate the as any in the update_substate function? It seems type-safe when directly invoking the update_state function, so it should also be safe when invoked indirectly, right? These functions are meant to be lightweight helpers ...

Utilizing Swift to Encode Arrays of Objects

I am having trouble converting a Swift Encodable struct into JSON that matches the required format: { "userID": 1000142, "emergencyContactData": {"contact": [ {"firstName": "John"}, {"lastName": "Doe"}, {"em ...

Incorporating Angular 4 with Angular CLI and ASP.Net MVC5 for seamless integration

Creating a hybrid application with Angular 4 and MVC 5 is my current project. I've set up the Angular 4 structure using angular-cli, but most of the information online only covers either: Manually integrating the two technologies, or Integrating MVC ...