Using ngFor in Angular to display the API response

I am having trouble displaying a JSON response in my web panel. When attempting to show the full response, everything works perfectly. However, when I try to use ngFor, I encounter the following errors in the browser:

ERROR TypeError: Cannot read property 'getContext' of null

ERROR TypeError: Cannot read property 'result' of undefined

This is the method I am trying to use:

<div *ngFor="let subject of lstresult.result.subject | json " class=" col-lg-4">
  <div class=" card card-chart">
    <div class=" card-header">
      <h5 class=" card-category">Completed Tasks</h5>
      <span>{{ subject | json }}</span>
      <br /><br />
    </div>
    <div class=" card-body">

    </div>
  </div>
</div>

The API request response class looks like this:

   export interface VatAPI {
      result: EntityResponse;
    }
    
    export interface EntityResponse {
      subject: Entity[];
      requestDateTime: string;
      requestId: string;
    }
    
    // Other interfaces...

The API request is as follows:

export class ApiService {
  constructor(private httpclient: HttpClient) {}
  getcomments(): Observable<any> {
    return this.httpclient.get(
      "https://wl-api.mf.gov.pl/api/search/nips/5213003700,6151001756?date=2020-07-27"
    );
  }
}

For some context, a full example response looks like this:

// Example JSON response data...

Component.ts code snippet:

this.ApiService.getcomments().subscribe((data) => {
  this.lstresult = data;
});

It might be a beginner mistake, but I'm struggling to resolve this issue ;)

Answer №1

It seems that the data has indicated a JSON response. Therefore, in order to properly display this information in HTML, you should implement the following changes:

<div *ngFor="let subject of lstresult.result.subjects" class=" col-lg-4">

Answer №2

1_ The API has already returned your response in JSON format, so there is no need to use the `json` pipe.

2_ngFor is attempting to access data within the lstresult object, but it is unable to do so because the data has not been loaded yet. Therefore, consider using the `async` pipe instead of the `json` pipe.

Answer №3

In my opinion, incorporating the async pipe within your ngFor loop is crucial due to the observable nature of your JSON results. By implementing a ngIf statement just above the ngFor loop, you can better manage and control the flow of data.

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

Ways to update a JSON object within an array of objects

I've got an array of objects // Extracted from the database $scope.users = [{"$id":"1","UserID":3,"Name":"A","Selected":false},{"$id":"2","UserID":4,"Name":"B","Selected":false},{"$id":"3","UserID":5,"Name":"C","Selected":false},{"$id":"4","UserID":6 ...

Encountering an "XML Parsing Error: no element found Location" error in AngularJS $http when JSON results are expected on a GET request

Whenever I try to make an angularjs $http GET request, I am faced with an XML parsing issue. Here is the code snippet for the $http call: $http({ method: 'GET', url: "myapp/api/items" + itemId }); The error message I receive is as fol ...

What is the generic type that can be used for the arguments in

One function I've been working on is called time const time = <T>(fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T> => { return new Promise(async (resolve, reject) => { const timer = setTimeout(() => r ...

Transform a JSON POST into a Python list

Hey everyone, I have received a list from a JSON post. Here's the JSON: {"Array":"[(1, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 5), (4, 6), (5, 6), (6, 7)]"} I'm looking to transform it into this format: type<class 'li ...

Converting JSON data to a different format using SwiftJSON

I am currently facing an issue with obtaining JSON data from web services using Alamofire + SwiftJSON as I am unable to convert the type JSON to another type. Here is an excerpt of my code: var product:JSON = [] override func viewDidLoad() { Alamof ...

What is the best way to integrate the jsoncpp library into a project using cmake and conan2?

Struggling with conan2, cmake, and the jsoncpp library at the moment. I've attempted to convert jsoncpp into a shared library using the jsoncpp/json/json.h path. Avoiding the command sudo apt install libjsoncpp as it complicates cross-platform compati ...

Tips on utilizing a function that was generated within the constructor

I'm currently in the process of developing a function within the constructor, and it is essential that this function be placed inside the constructor. I am interested in implementing a button to trigger this function from an external source, but unfor ...

Methods for updating an object in an mLab collection by its _id

My backend API currently has the ability to update an array, but I am encountering an issue where it only updates the first item in the collection and does not reference the _id. Even when I try to edit values for other objects in the array, it always just ...

Change an XML file to a JSON dump in Python

Hello there! I am looking to convert an XML file into a JSON dump. I have already attempted the following: for i in cNodes[0].getElementsByTagName("person"): self.userName = i.getElementsByTagName("login")[0].childNodes[0].toxml() self.use ...

Issue encountered while executing ./node_modules/.bin/cucumber-js within GitLab CI

I've encountered an issue while setting up a continuous integration build for my node project. Despite the fact that npm run test runs smoothly in my local setup, I am facing an exception in GitLab CI. The error arises from the following test command ...

I am unable to run ng serve at the moment

Every time I enter ng serve it shows: Your global Angular CLI version (10.0.1) is higher than your local version (6.2.9). The local Angular CLI version will be used. To prevent this warning, use ng config -g cli.warnings.versionMismatch false. Schema va ...

Tips on updating icons automatically

Incorporating Ionic Angular, Font Awesome, and Stripe into my app, I encounter a challenge. I aim to dynamically change the icon on the HTML page based on data received from the server in the .ts page. This is the current setup: <ion-item *ngFor="let ...

Is it possible to clean up the response JSON returned from a Spring MVC Controller by utilizing a JSON Sanitizer

Is there a way to intercept the JSON returned from a Spring MVC Rest Controller in order to sanitize it and ensure it is valid, escaping any potentially harmful characters? I am considering using the OWASP JSON Sanitizer for this purpose. We currently rel ...

What is the process for detecting command line arguments within the package.json script section?

I am working with the package.json file, which includes the following script: { "scripts": { "test": "ng test", }, ... } Now, I need to execute the command below: npm run test --prod How can I determine if the flag - ...

Selecting a particular item in a list depending on time using JavaScript, jQuery, or Angular

When working with a JSON file and binding it to list items, I have included a name/value pair in the json for each line indicating audio time, such as "time like 0, 5, 10 in seconds form". In my Cordova application, I am using a media plugin and implement ...

Step-by-step guide on Setting up the bronto.sca.cart object using Bronto JSON

I have implemented the Bronto Tag Manager to track cart details successfully. After including the Bronto Commerce JavaScript snippet on my page, I am now able to create the bronto.sca object. While bronto.sca.config() and bronto.sca.id are returning valu ...

Displaying JSON data dynamically by iterating through it in a loop

While working with JSON data in a loop, I noticed that the code quality does not meet my expectations. I have a feeling that I might be missing something in my approach. $(function(){ $.getJSON('data.json', function(data){ let content ...

Utilizing JSON Data in MVC View .cshtml: A Comprehensive Guide

I am seeking assistance with a challenge I am facing. I have a web service that returns JSON data in the following format: {"stations":[{"name":"aname","free":false},{"name":"anothername","free":true}]} This JSON consists of an array of objects, each con ...

What could be the reason for certain Angular modules importing successfully while others fail to do so?

I am encountering an issue with a module that I am struggling to import. Using Typescript 2.7 and Node 10 The pxl-ng-security module is showing an error in both VSCode and VS2019. When hovering over it, error 2307 is displayed. Below is the import secti ...

Dependency Injection: The constructor of the injectable class is called multiple times

There are multiple classes that inject the TermsExchangeService: import {TermsExchangeService} from './terms-exchange.service'; @injectable() export class TermsExchangeComponent { constructor( private termsExchangeService: TermsExchan ...