Data not showing up in *ngFor loop

component.ts file

posts= [];
  constructor( private http:HttpClient) { 
    http.get('https://jsonplaceholder.typicode.com/posts')
    .subscribe(response=>{
      this.posts.push(response)
      console.log(this.posts)
    });
  }

Within the HTML file

<ul class="list-group">
  <li 
    *ngFor="let post of posts"
    class="list-group-item">{{post.title}}</li>
</ul>

While I can successfully see the data from array in the console log, the *ngFor directive appears to only display an empty container. Strange!

Answer №1

The response of

https://jsonplaceholder.typicode.com/posts
is an array of objects.

[
  {
   userId: 1,
   id: 1,
   title: "sunt aut facere repellat",
   body: "quia et suscipit suscipit recusandae consequuntur"
  },
 {
   userId: 1,
   id: 2,
   title: "qui est esse",
   body: "est rerum tempore vitae sequi"
 },
]

Instead of pushing an array of objects within another array, you just need to assign the response directly.

Define a posts interface instead of using any[] for type casting

export interface IPosts = {
  userId: number;
  id: number;
  title: string;
  body: string;
}

Now fetch data from the endpoint

posts: IPosts[]; // Notice the proper type assignment.

constructor(private http:HttpClient) { 

const url = 'https://jsonplaceholder.typicode.com/posts';
http.get(url).subscribe((response: IPosts[]) => this.posts = response)}

In the template, iterate through the results.

<ul class="list-group" *ngIf="posts.length">
  <li 
    *ngFor="let post of posts"
    class="list-group-item">{{post.title}}</li>
</ul>

Answer №2

The data retrieved from

https://jsonplaceholder.typicode.com/posts
consists of an array of objects. However, instead of using Array.push() to add items to the posts array, you are mistakenly overwriting it with just one item (an array of objects) that lacks a title property.

To correct this issue, consider the following approach:

  posts = [];

  constructor( private http:HttpClient) { 
    http.get('https://jsonplaceholder.typicode.com/posts')
    .subscribe(response=>{
      this.posts = response
      console.log(this.posts)
    });
  }

An alternative solution is to utilize the async pipe in this scenario

 posts = this.http.get('https://jsonplaceholder.typicode.com/posts');

 constructor( private http:HttpClient) {}

<ul class="list-group">
  <li *ngFor="let post of posts | async" class="list-group-item"> 
     {{post.title}}
  </li>
</ul>

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

How can you update ngModel in Angular and mark the form as dirty or invalid programmatically?

My form is connected to a model as shown below In the component file: myTextModel: string; updateMyTextModel(): void { this.myTextModel = "updated model value"; //todo- set form dirty (or invalid or touched) here } Html template: <form #test ...

Tips for preventing an AJAX response from populating a select dropdown

https://i.sstatic.net/gA1VE.gif In the example above, there is a placeholder (an option without value) that says something like Select Subcategory. When I change the category value, the subcategories are displayed. But what I want is for the subcategory ...

Downloading Laravel Excel Files via an Ajax Call

Is it possible to generate an Excel file using Laravel with PHPSpreadsheet (PHP lib) and then send the XLSX file to the frontend for download? JSX Section axios .get( "/excel/export/dashboardTable", {} ) .then(resp => { //success call ...

Issue encountered while retrieving information from an external API

I am facing an issue with my HTML page that includes Google ADWords and an ajax call from an external URL to retrieve JSON data. The external API has been created by me, and the API Controller in Laravel 5.2 looks like this: public function index() { ...

Executing numerous TypeScript 'tsc' commands

I'm currently working on setting up an NPM command to transpile two separate Typescript projects located in subdirectories within my application, followed by starting the server. Within my 'src' public folder, I have 'Server' and ...

What is the proper way to trigger a nested jQuery function in HTML?

When calling the addtext() function from onclick() in HTML, nested inside the add() function, how can I go about calling the second function? Here's a link with the add() function that displays a textbox and an ADD button invoking the addtext() funct ...

Looping through JQuery change events

I have a challenge with handling checkboxes. Whenever a user checks one, I need to validate if they are permitted to do so. If not, I must notify them and uncheck the box. However, this process becomes recursive as it triggers the change event again! How c ...

Storing the outcome of a query into a variable in Node-RED

I am facing an issue where I need to transfer the value of Object[0] nazwa, which is obtained from a query result (let's say "ab" in this scenario), to another variable. Since I am new to red node and JS, I'm unsure about how to accomplish this t ...

Populate an AngularJS select dropdown with JSON data and automatically pre-select the specified value

I am currently dealing with 2 entities: project and project_types. Each project can have one or multiple project_types associated with it. Using ajax (ng-init), I am retrieving the project data (including its related project_types) and all available proje ...

Which is better for a jQuery/Ajax Login Box: JSONP or CORS?

To create a login box that meets the specified criteria, the following must be taken into consideration: Develop it as a versatile UI Component that can be utilized in various sections of a website Allow for multiple instances of this component to coexis ...

An error occurred in jQuery.ajax: The object's property 'xhr' is not a function

I'm facing an issue with a jQuery.ajax object where I am trying to replace xhr. When I run the code below, it throws an error: TypeError: Property 'xhr' of object #<Object> is not a function The part of the code causing the error is ...

What is the best way to extract the requested URL from an AJAX response?

Within my project, I have incorporated several ajax global events. When using the following code: $(document).ajaxSend(function(event, jqxhr, settings) { // }); I am able to retrieve the requested URL from settings.url. However, I am uncertain abou ...

The app's connection issue persists as the SDK initialization has exceeded the time limit

We are currently facing an issue when trying to publish a new manifest for our app in the store. The Microsoft team in India is encountering an error message that says "There is a problem reaching the app" during validation. It's worth noting that th ...

Develop an innovative showcase page showcasing 151 individual profiles with React Router

I am new to using React Router and feeling a bit confused about how to proceed. On my homepage, I have 151 unique monster thumbnails. When a user clicks on a thumbnail, they should be directed to the specific monster's 'show page'. Currently ...

Guide to inserting nested arrays into a MongoDB database using Node.js

I'm attempting to send Product data to a mongo database using mongoose. Product Model var mongoose = require('mongoose'); var Schema = mongoose.Schema; var productsSchema = new Schema({ // productId: {type: _id, required: true, au ...

Animating nested child routes with framer-motion in react-router-dom version 6.4.3



I recently updated to the latest version of react-router-dom and their new Data APIs, which required me to rewrite my app's routing logic using object-based routing instead of the V5 JSX syntax with Routes. I'm curious if anyone has been su ...

Indicate when a ReplaySubject has reached its "completion" signal

I'm currently looking for an effective way to indicate when a ReplaySubject is empty. import {ReplaySubject} from 'rxjs/ReplaySubject'; const rs = new ReplaySubject<Object>(); // ... constructor(){ this.sub = rs.subscribe(...); } ...

Load link dynamically using the rel attribute

I am trying to implement dynamic content loading using jQuery's .load() function. The links are stored in the .rel attribute of the anchor tags. My setup looks like this: <script> $(document).ready(function(){ $('.sidebar_link').clic ...

The arrow icon for selecting input in Material Dashboard React is missing

Source Code View Result Why is the arrow icon not visible when viewing the select like this? I am using "@mui/material": "^5.8.6". Can someone please help me with this? <Box sx={{ width: "auto" }}> <FormControl fullWidth> ...

The HTMLElement type does not include the Ionic typescript property

I am currently using Ionic v3 with TypeScript. My goal is to store the file_url in an array after checking if its width is equal to twice its height. However, I am encountering an error: The 'name_array' property does not exist on the ' ...