Angular: 无法在组件的 HTML 页面中显示从 Http Response 接收到的对象数组

Angular: Cannot display the array of objects received from the Http Respnse in the HTML page of Component

component.ts 文件

import { Component, OnInit } from '@angular/core';
import {HttpClient, HttpErrorResponse} from '@angular/common/http'
import {Observable} from 'rxjs';
import { error } from 'selenium-webdriver';
import { HttpEventType } from '@angular/common/http/src/response';
interface Todo {
  result: string[];
}
@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})

export class UsersComponent implements OnInit {

  constructor(private http: HttpClient) { }
  results: String[];
  ngOnInit(): void {
    this.http.get<Todo>('http://localhost:3000/todos').subscribe(data => { 
      this.results = data.result;
      console.log(data);
    },    (err: HttpErrorResponse) => {
      if (err.error instanceof Error) {
        // A client-side or network error occurred. Handle it accordingly.
        console.log('An error occurred:', err.error.message);
      } else {
        // The backend returned an unsuccessful response code.
        // The response body may contain clues as to what went wrong,
        console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
      }
    }
    );
  }

}

component.html 文件

<div>Works</div>
<ul>
  <li *ngFor="let result of results">{{result.text}}</li>
</ul>

我得到一个 HTTP 304 状态代码,返回的数据是一个对象数组。 Http响应返回的json数据:

0: Object { _id: "5a53460339ff2c2488a7bee1", text: "Invade the north tower", __v: 0, … }
1: Object { _id: "5a53464539ff2c2488a7bee2", text: "Collect invisibility rune from Dunaki", __v: 0, … }
2: Object { _id: "5a53465b39ff2c2488a7bee3", text: "Meet Shinoko", __v: 0, … }
3: Object { _id: "5a53585a62ce2331a889556e", text: "xyz", __v: 0, … }
4: Object { _id: "5a5450ce486ddb1e184567ae", __v: 0, date: "2018-01-09T05:19:10.713Z" }

数据被检索并存储在组件的 results 数组中,但未显示在 html 中。 在观察控制台时,我注意到 html 首先呈现,然后收到响应。但是我已经在 ngOnInit() 中提到了检索逻辑。 请指导我,谢谢!

您必须在 ngAfterViewInit() 方法中填写列表。这就是 ngOnInit 首先工作的原因。加载 HTML 后,ngAfterViewInit 开始工作。

不应该是这一行:

this.results = data.result;

就是这样:

this.results = data;

您在 console.log 中只显示了 data,我没有看到它有 result 属性?

根据以下评论更新: 这是注释中链接到此 post:

的示例代码
http.get<ItemsResponse>('/api/items').subscribe(data => {
  // data is now an instance of type ItemsResponse, so you can do this:
  this.results = data.results;
});