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

Angular 角度';的新http客户端错误无法读取属性';数据';未定义的,angular,Angular,我正在学习如何使用angular的新http客户端模块。当我尝试使用rest api时,我得到一个错误:无法读取未定义的属性“data”。 这是我的app.html <div style="text-align:center"> <h1> Welcome to {{title}}! </h1> <button (click)="getPosts()">Get Posts</button> <div *ngF

我正在学习如何使用angular的新http客户端模块。当我尝试使用rest api时,我得到一个错误:无法读取未定义的属性“data”。 这是我的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>

欢迎来到{{title}}!
发帖
{{result}json}
这是我的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);
  }
}
从'@angular/core'导入{Component,OnInit};
从'@angular/common/http'导入{HttpClient};
接口项响应{
数据:任何[];
}
@组成部分({
选择器:'应用程序根',
templateUrl:“./app.component.html”,
样式URL:['./app.component.css']
})
导出类AppComponent实现OnInit{
结果:有;
//将HttpClient注入组件或服务。
构造函数(私有http:HttpClient){}
头衔=‘学校2学院’;
ngOnInit():void{
}
getPosts(){
this.http.get('https://reqres.in/api/users?page=3)。订阅(res=>
这是(结果=res);
}
}

为什么我会出现无法读取未定义属性“data”的错误?

由于您正在发出异步请求,最初结果将是未定义的,请使用
安全导航操作符检查结果是否存在,然后访问数据

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

{{result}json}

无法读取未定义的属性“数据”仅表示导致未定义。放置console.log或应用断点,并尝试找出未定义断点的原因。当我们应用断点时,我们可以找到未定义断点的确切原因。了解原因很重要。

问题与@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>
导出类AppComponent实现OnInit{
结果:数组=[];//代码已更改
...
getPosts(){
this.http.get('https://reqres.in/api/users?page=3)。订阅(res=>
this.results=res.data);//代码已更改
}
}
{{result}json}
2)使用安全导航操作员

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

{{result}json}
但使用第二种方法是标准做法


什么是安全导航操作员?你能再解释一下吗?当试图访问不存在的对象的对象属性时,可以使用安全导航操作符来防止Angular抛出错误。更好的方法是什么?您也可以选择使用ngIF,但在sanjeetharan银行这将是更好的选择。答案被接受。如果你把我的问题投赞成票会很好吗?谢谢,它成功了。但是我想从服务访问getposts()方法,然后从app.component.ts订阅该函数?谢谢。如果您可以投票表决我的问题,那就太好了。服务:getPosts(){返回this.http.get('=>res.json());}组件:this.postService.getPosts().subscribe(res=>this.results=res.data);感谢您的回答:)没有必要使用res.json转换为json