A comprehensive guide on displaying data in Angular using an API

I have encountered an issue while trying to display data from an API in the 'home.component.html'. Although my 'home.component.ts' successfully fetches the data from the service, I'm facing difficulty rendering it in 'home.component.html'. It seems like I might be handling the data incorrectly.

The error message I receive is: Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed.

Here is a snippet of my 'home.component.html':

<div class="wrapper">
    <mat-card class="example-card" *ngFor="let data of datas; index as i">

        <mat-card-header>
            <div mat-card-avatar class="example-header-image"></div>
            <mat-card-title>{{ data.attributes.name }}</mat-card-title>
            <mat-card-subtitle>{{ data.attributes.publishedAt | date:'medium' }}</mat-card-subtitle>
        </mat-card-header>
        
        <img mat-card-image [src]="data.attributes.image.data.attributes.url" alt="meme">

    </mat-card>
</div>

And here is an excerpt from my 'home.component.ts':


import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/services/data.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {


  datas:any=[];
  errores:string="";
  totalLength:any;

  constructor(private data: DataService) { 
  }

  ngOnInit(): void {

    this.data.getMemes().subscribe(res=>{

     const myJSON = JSON.stringify(res); 
  
     this.datas = myJSON;

     this.totalLength = res.length;

    }, error =>{
      console.log(error);
        if(error.status == 0){
            this.errores="Código del error: "+error.status+" \n Ha ocurrido un error del lado del cliente o un error de red.";
        }else{
            this.errores="Código del error: "+error.status+"\n\n"+error.statusText;
        }
    })  

  }

}


The error displayed in the browser console:

This is the structure of the JSON data returned by the API response, containing an array named 'data' with three objects:


{
  "data": [
    {
      "id": 1,
      "attributes": {
        "name": "black",
        "createdAt": "2023-01-17T19:18:29.362Z",
        "updatedAt": "2023-01-17T19:50:47.247Z",
        "publishedAt": "2023-01-17T19:37:56.037Z"
      }
    },
    {
      "id": 2,
      "attributes": {
        "name": "jennie",
        "createdAt": "2023-01-17T19:49:28.235Z",
        "updatedAt": "2023-01-17T19:51:07.573Z",
        "publishedAt": "2023-01-17T19:49:33.399Z"
      }
    },
    {
      "id": 3,
      "attributes": {
        "name": "pink",
        "createdAt": "2023-01-17T19:50:31.818Z",
        "updatedAt": "2023-01-17T19:50:56.444Z",
        "publishedAt": "2023-01-17T19:50:32.786Z"
      }
    }
  ],
  "meta": {
    "pagination": {
      "page": 1,
      "pageSize": 25,
      "pageCount": 1,
      "total": 3
    }
  }
}

Finally, this is my 'data.service.ts':


import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { environment } from 'src/environments/environment.prod';



@Injectable({
  providedIn: 'root'
})
export class DataService {

  REST_API: string ='http://localhost:1337/api/memes';

  httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');

  constructor(
    private http: HttpClient
  ) {  }

  getMemes():Observable<any> {

    let API=this.REST_API;
    return this.http.get(API,{headers:this.httpHeaders}).pipe(
      map((data:any) => { 
        return data;
      }), catchError( error => {
        return throwError(error);
      })
    );

  }



}


Answer №1

What is the reason for attempting to convert JSON.stringify to an array object:

const myJSON = JSON.stringify(res);
this.datas = myJSON;

It is unnecessary to stringify the "res" object, simply pass res.data directly :

this.datas = res.data;

Also, please be aware that your res object does not contain a "length" property :

this.totalLength = res.length

You can achieve the desired result like this:

this.totalLength = res.meta.pagination.total:

Additionally, there seems to be an incorrect property call in your HTML view as the image property is not present in data.attributes:

<img mat-card-image [src]="data.attributes.image.data.attributes.url" alt="meme">

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

What is the best way to incorporate a dynamic background in NextJS using Tailwind?

I have a poster image that I want to use as a background image, fetched from MovieDb. I tried putting it inside the className like this: className={bg-[url('${path}')] h-screen bg-cover bg-center text-white border-b-8 border-b-solid border-b-sla ...

Having trouble with the ionic ion-nav-buttons not working on initial load?

My table view triggers the PixCtrl controller when a cell is clicked. If the connection is successful, data is retrieved using $http.get, otherwise sqlite is used. This setup works fine. However, I am facing an issue with my ion-nav-buttons being dynamic. ...

Automatically switch slides and pause the carousel after completing a loop using Bootstrap 5 Carousel

Seeking assistance with customizing the carousel functionality. There seems to be some issues, and I could use a hand in resolving them. Desired Carousel Functionality: Automatically start playing the carousel on page load, and once it reaches the end of ...

Having trouble using jQuery's .off() method to remove an event handler?

I'm facing an issue with my jQuery code where the .off('click') method doesn't seem to be working. I've tried removing the event binding from '.reveal-menu', but it's not working as expected. The initial animation wo ...

Error: Expecting only one React element child to be passed into React.Children.only() function

I am encountering an issue while attempting to construct a web table using the antd library. The exact error message reads: "react.development.js:1251 Uncaught Error: React.Children.only expected to receive a single React element child". I have been stru ...

The error stating that document.getElementById(...) is null has occurred within RSForms due to a TypeError

Issue: When clicking on the form to continue, a TypeError: document.getElementById(...) is null error occurs. Can anyone help me fix this problem? When I click on the continue button, it calls the function submitForm. <script type="text/javascript"> ...

Guidelines for Nestjs class-validator exception - implementing metadata information for @IsNotIn validator error handling

I have a NestJs data transfer object (dto) structured like this import { IsEmail, IsNotEmpty, IsNotIn } from 'class-validator'; import { AppService } from './app.service'; const restrictedNames = ['Name Inc', 'Acme Inc&ap ...

Using HTTP POST in a Firefox Extension using JavaScript

As a beginner, I am attempting to execute a basic HTTP post in JS using a Firefox extension. I'm encountering an issue where the parameters are not being passed as expected: var params = "a=1&b=2&c=3" req.open('POST', 'http:// ...

Optimal approach to configuring Spring Boot and Angular for seamless communication with Facebook Marketing API

Currently, I am working on a Spring Boot backend application and incorporating the Facebook marketing SDK. For the frontend, I am utilizing Angular 10. Whenever I create a new page or campaign, my goal is to send the corresponding object back to the fronte ...

Determine the hour difference between two provided dates by utilizing the date-fns library

My API returns a "datePublished" timestamp like this: "2019-11-14T14:54:00.0000000Z". I am attempting to calculate the difference in hours between this timestamp and the current time using date.now() or new Date(). I am utilizing the date-fns v2 library fo ...

What steps can I take to ensure that the original field does not regain focus once the dialog is closed?

My users prefer not to switch from the keyboard to mouse while filling out an input form. To address this, I am using the onFocus event to display a JQuery UI Dialog. However, when I use the dialog's close(); function, the dialog reopens as the origin ...

Creating a simulation of a JavaScript callback within a C# host program

Currently, I am in the process of developing a c# application with an embedded web browser control. In this project, I'm facing a challenge where I need to call a C# method from JavaScript and pass a JavaScript callback using the dynamic technique exp ...

Tips for optimizing the "framerate" (setInterval delay) in a JavaScript animation loop

When creating a JavaScript animation, it's common practice to use setInterval (or multiple setTimeouts) to create a loop. But what is the optimal delay to set in these setInterval/setTimeout calls? In the jQuery API page for the .animate() function, ...

Passing parameters in a jQuery function through a button click

I am trying to figure out how to pass the @item.Id value as a parameter in the click function for a button. Here is the code snippet: <button id="buttonEdit" style="color:darkgreen" data-toggle="modal" data-target="#Ed ...

Regex struggles to identify words containing foreign characters

Here is a method I have created to check if a user-input term matches any blacklisted terms: static checkAgainstBlacklist(blacklistTerms, term) { return blacklistTerms.some(word => (new RegExp(`\\b${word}\\b`, 'i&ap ...

AssertionError [ERR_ASSERTION]: The value of undefined is not equal to 390 in the GitLab

I'm a bit confused about the AssertionError [ERR_ASSERTION]: undefined == 390 in Gitlab. What I need is: The sumSalaries(obj) function, which should take an object obj as a parameter where the field names correspond to the employee's name and t ...

The method firebaseApp.auth does not exist in user authentication using Firebase

Implementing user authentication with Firebase in my React webapp has been a challenge due to issues with the firebaseAuth.app() function. Despite trying various solutions such as reinstalling firebase dependencies, updating imports to SDK 9 syntax, and ad ...

Angular allows for the creation of a unique webpage layout featuring 6 divs

I am working on a project where I have an image of a car and I need to overlay 6 divs onto the image which can be selected with a mouse click. When a user clicks on one of the divs, it should change color. I've attempted using z-index, but it doesn&ap ...

Warning: Next.js is throwing a hydration error because the server HTML does not include a matching <main> element within a <div>

I have been encountering hydration issues in my next.js application. After extensive troubleshooting, I have found that the culprit might be the higher order component called withAuth.js The error message displayed is: Warning: Expected server HTML to con ...

I'm wondering if you have any insights on how to retrieve objects using Mono WebAssembly

I am looking to send a c# object back via mono-wasm, but when I attempt to do so, the returned object appears in my JavaScript file here. The C# code can be found in [image2]: C# code My JavaScript code can be found here: JS code Everything seems to wor ...