ngFor 在数组中仅返回 1 项时不显示

ngFor not displaying when only 1 item returned in array

我有一个从 REST API 调用中收集的 json 数组,如下所示:

[ 
    {"id":1,"title":"Title One","author":"Auth One"},
    {"id":2,"title":"Title Two","author":"Auth Two"},
    {"id":3,"title":"Another Title","author":"Another author"}
]

我创建了一个 class posts.model.ts 来表示 post 的组成:

export class Post {
    id: Number;
    title: string;
    author: string;
}

我的view-component.component.html(我知道这个名字不好意思,抱歉)如下所示:

<p>
    Post ID:<br>
    <input type="text" [(ngModel)]="id">
</p>
<p>
    <button (click)="search()">Search</button>
</p>
<div *ngIf="PostList">
    <div *ngFor="let post of PostList">
        Post ID: {{post.id}}<br>
        Post Title: {{post.title}}<br>
        Post Author: {{post.author}}
        <hr>
    </div>
</div>

和我的 view-component.component.ts 像这样

import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Post } from './post.model';

@Component({
  selector: 'app-view-component',
  templateUrl: './view-component.component.html',
  styleUrls: ['./view-component.component.css']
})
export class ViewComponentComponent implements OnInit {

  @Input('post') post: Post;
  id: string = "";
  PostList: any = [];

  constructor(private http: HttpClient) { }

  ngOnInit(): void { }

  search() {
    this.http.get('http://localhost:3000/posts/' + this.id)
    .subscribe((data: {}) => {
      this.PostList = data;
      console.log("This is what I got back = " + JSON.stringify(data));
    })
  }

}

我观察到的是,当我单击输入字段中没有任何内容的按钮时(我希望返回所有 posts(这按预期工作,我得到了所有的完整列表posts))。

然而,当我在输入字段中输入例如数字“2”并单击按钮时,我希望只看到显示的第二个 post ("Title Two" "Auth Two"),但是什么也没有显示。

正如您在“.ts”文件中看到的那样,我将在 search() 函数中返回的字符串写到控制台。当我搜索第二个 post 时,我确实得到了以下信息:

This is what I got back = {"id":2,"title":"Title Two","author":"Auth Two"}

但是,html 页面上没有显示任何内容。

现在你 return 一个 object。您需要 return 一个 array 和后端的 1 个元素:

[{"id":2,"title":"Title Two","author":"Auth Two"}]

以下是我的实现方式:

  • 我会用 interface 而不是像这样 class

    export interface Post {
        id: Number;
        title: string;
        author: string;
    }
    
  • 然后我会在数组声明 PostList: Post[]; 中使用创建的接口,我也会将其保留为未定义,以便 <div *ngIf='PostList'> 起作用,因为只有在以下情况下检查才会为假数组未定义。

  • 我也会在调用API this.http.get<Post[]>时使用该接口,并在从API .subscribe((data: Post[]) => [=]接收数据时再次使用它18=]

    this.http.get<Post[]>('http://localhost:3000/posts/' + this.id)
        .subscribe((data: Post[]) => {
          this.PostList = data;
          console.log("This is what I got back = " + JSON.stringify(data));
        })
    

如果需要,请随时与我联系以获得进一步的帮助。