Angular 服务数据未显示

Angular service data not getting displayed

我尝试显示对象列表(这里是用户,但我需要显示很多其他类型),当我尝试按照教程进行操作时,它在我的屏幕上什么也没有显示。

而当我从 Github 启动完整的构建教程时,它有效。

我做错了什么?

这是我的代码。如果您需要其他东西,请告诉我。

我在Angular 7.

工作

用户列表组件

import { Component, OnInit } from '@angular/core';
import {Router} from "@angular/router";
import {UserService} from "../core/user.service";
import {User} from "../model/user.model";
export class UserListComponent implements OnInit {

  users: User[];

  constructor(private router: Router, private userService: UserService) { }

  ngOnInit() {
    this.userService.getUsers()
      .subscribe( data => {
        this.users = data;
      });
  }
}

用户服务

@Injectable()
export class UserService {
  constructor(private http: HttpClient) { }
  baseUrl: string = 'http://localhost:8080/api/user';

  getUsers() {
    return this.http.get<User[]>(this.baseUrl);
  }
}

用户-list.component.html

<div class="col-md-6">
  <h2> User Details</h2>
  <table class="table table-striped">
    <thead>
    <tr>
      <th>Id</th>
      <th>Email</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let user of users">
      <td>{{user.id}}</td>
      <td>{{user.email}}</td>
    </tr>
    </tbody>
  </table>
</div>

当我 alert(data[0].mail) 我有正确的邮件,但是当我尝试显示它时用户仍然是空的

您正在接收用户异步。 因此,当页面首次呈现时,用户还不在那里。 (弹窗会在之后显示,所以他们会)

您需要为页面使用异步方法以了解数据将在第一次呈现和重新呈现后更新。

export class UserListComponent implements OnInit {

  users$: Observable<Users>; // Using Observable

  constructor(private router: Router, private userService: UserService) { }

  ngOnInit() {
    this.users = this.userService.getUsers()
  }
}

如您所见,我正在使用 Observable 道具。这将在每次更改时通知。

<div class="col-md-6">
  <h2> User Details</h2>
  <table class="table table-striped">
    <thead>
    <tr>
      <th>Id</th>
      <th>Email</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let user of users$ | async">
      <td>{{user.id}}</td>
      <td>{{user.email}}</td>
    </tr>
    </tbody>
  </table>
</div>

并通过 在 HTML 文件中指定| async 管道表示此道具是异步的,并且将要更新。

异步管道: https://angular.io/api/common/AsyncPipe

观察值: https://angular.io/guide/observables