Angular 的新 http 客户端错误无法读取未定义的属性"数据"



我正在学习如何使用angular的新http客户端模块。当我尝试使用其余 API 时,我收到错误无法读取未定义的属性"数据"。这是我的应用程序.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>

这是我的应用程序.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);
  }
}

为什么我收到错误无法读取未定义的属性"数据"?

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

<div *ngFor="let result of results?.data">
      {{ result | json }}
 </div>

问题与@Sajeetharan解释相同:

由于您正在发出异步请求,因此最初的结果将是 定义

您可以通过两种方式解决它:

1)从一开始就提供一些初始值:

export class AppComponent implements OnInit {
    results:Array<any> = []; // code changed
    ...
    getPosts() {
        this.http.get<ItemsResponse>('https://reqres.in/api/users?page=3').subscribe(res =>
        this.results = res.data); // code changed
    }
}

<div *ngFor="let result of results">
   {{ result | json }}
</div>

2) 使用安全导航运算符

<div *ngFor="let result of results?.data">
    {{ result | json }}
</div>

但使用第二种方式是标准做法。

无法读取未定义的属性"数据"仅表示结果未定义。放置控制台.log或应用断点并尝试找出未定义的原因。当我们应用断点时,我们可以找出它未被定义的确切原因。了解原因很重要。

最新更新