Angular 2 *ngFor 不打印到 table

Angular 2 *ngFor does not print to table

我是 Angular 的新手,我在显示从数据库检索的数据时遇到了问题。有人能帮我理解为什么当我在这个 HTML 代码上使用 *ngFor 时,只显示在我的 html 而不是其余行上吗?

这是我的 HTML 文件

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Lastname</th>
            <th>Email</th>
            <th>Phone</th>
            <th>School</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let contact contacts$">
            <td>{{ contact.first_name }}</td>
            <td>{{ contact.last_name }}</td>
            <td>{{ contact.email }}</td>
            <td>{{ contact.phone_number }}</td>
            <td>{{ contact.school }}</td>
        </tr>
    </tbody>
</table>

这是我的 component.ts 文件

import { Component, OnInit } from '@angular/core';
import { ContactService } from "./contacts.service";
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Contact } from './contact'

@Component({
  selector: 'app-contacts',
  templateUrl: './contacts.component.html',
  styleUrls: ['./contacts.component.css']
})

export class ContactsComponent implements OnInit {

  constructor( private router:Router, private contactService: ContactService )
  {}
    contacts$: Observable<Contact[]>;

    ngOnInit() {
        this.contacts$ = this.contactService.getContacts();
    }
}

我从 GET HTTP 调用中获取我的信息,如果我在标签上执行 *ngFor 它工作正常,但当我在标签上使用它时它不显示

这是我在

上执行此操作时的代码

<div *ngFor="let contact of contacts$ | async" >
  {{contact.first_name}}
</div>

据我所知,您的 *ngFor tr 标签中缺少 of。 您的 HTML 代码应该如下所示

<tbody>
        <tr *ngFor="let contact of contacts$"> <!-- adding of to retrive data -->
            <td>{{ contact.first_name }}</td>
            <td>{{ contact.last_name }}</td>
            <td>{{ contact.email }}</td>
            <td>{{ contact.phone_number }}</td>
            <td>{{ contact.school }}</td>
        </tr>
    </tbody>

希望对您有所帮助。

您没有编写正确的循环语法,就像在本例中您遗漏了“of”并交叉检查正确的 属性 名称。

<tbody>
  <tr *ngFor="let contact of contacts">
    <td>{{ contact.first_name }}</td>
    <td>{{ contact.last_name }}</td>
    <td>{{ contact.email }}</td>
    <td>{{ contact.phone_number }}</td>
    <td>{{ contact.school }}</td>
  </tr>
</tbody>