【问题标题】:Angular service data not getting displayed角度服务数据未显示
【发布时间】:2019-02-09 22:28:07
【问题描述】:

我尝试显示对象列表(此处为用户,但我需要显示许多其他类型),当我尝试按照教程进行操作时,它在我的屏幕上什么也不显示。

而当我从 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);
  }
}

用户列表.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) 我有正确的邮件,但当我尝试显示它时用户仍然是空的

【问题讨论】:

  • 您是否在托管此服务器的某个地方运行了 API 服务器:http://localhost:8080/api/user
  • 嗨,是的,当我发出警报时(数据[0].mail);我收到一个显示正确邮件的弹出窗口。
  • 请更新.html并导入.ts
  • 添加了 html 和导入

标签: angular promise angular-promise angular7


【解决方案1】:

您正在异步接收用户。 因此,当页面第一次呈现时,用户还没有出现。 (弹出窗口会在之后显示,所以他们会)

您需要对页面使用异步方法才能知道数据将在第一次渲染和重新渲染后更新。

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 管道表明此 prop 是异步的,并且将要更新。

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

可观察的: https://angular.io/guide/observables

【讨论】:

  • 这是一个正确的答案。另一种可能性是在您的模板中使用 elvis 运算符:{{user?.email}} 而不是异步管道..
  • 感谢您的回答,它有效,但它没有解释为什么我尝试的一些教程有效而我的代码没有。
  • @Boffbad 您的教程必须或用户 Observables 或在设置数据之前延迟显示页面,或在本地加载数据(意思是同步的)
猜你喜欢
  • 2018-03-06
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 2021-04-28
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 2021-06-04
相关资源
最近更新 更多