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

时间:2018-01-09 07:46:20

标签: angular templates ngfor

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()中提到了检索逻辑。 请指导我,谢谢!

2 个答案:

答案 0 :(得分:1)

不应该这一行:

this.results = data.result;

就是这样:

this.results = data;

您在console.log中只显示data,但我发现它没有result属性?

以下评论更新: 这是本帖子评论中链接的示例中的代码:

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

答案 1 :(得分:0)

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