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?