Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular's new http client error Cannot read property 'data' of undefined

Tags:

angular

I am learning how to use angular's new http client module. I get the error Cannot read property 'data' of undefined when I try to consume the rest api. Here's my app.html,

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!
  </h1>
  <button (click)="getPosts()">Get Posts</button>
  <div *ngFor="let result of results.data">

      {{ result | json }}

    </div>
</div>

Here's my app.component.ts

import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';

interface ItemsResponse {
  data: any[];
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  results: any;
  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}
  title = 'School2College';

  ngOnInit(): void {
  }
  getPosts() {
    this.http.get<ItemsResponse>('https://reqres.in/api/users?page=3').subscribe(res =>
      this.results = res);
  }
}

Why do I get the error Cannot read property 'data' of undefined?

like image 344
Karty Avatar asked Jun 29 '26 10:06

Karty


1 Answers

Since you are making a asynchronous request, initially results will be undefined, use a safe navigation operator to check if the results exists and then access the data

<div *ngFor="let result of results?.data">
      {{ result | json }}
 </div>
like image 144
Sajeetharan Avatar answered Jul 02 '26 04:07

Sajeetharan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!