Angular的新HTTP客户端错误无法读取未定义的属性“数据" [英] Angular's new http client error Cannot read property 'data' of undefined

查看:55
本文介绍了Angular的新HTTP客户端错误无法读取未定义的属性“数据"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何使用angular的新http客户端模块.我在尝试使用其余api时收到错误消息无法读取未定义的属性'data'". 这是我的app.html,

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>

这是我的app.component.ts

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);
  }
}

为什么会收到错误消息无法读取未定义的属性'data'?

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

推荐答案

由于您正在发起异步请求,因此最初的结果将是不确定的,请使用 safe navigation operator 来检查结果是否存在,以及然后访问数据

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>

这篇关于Angular的新HTTP客户端错误无法读取未定义的属性“数据"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆