我尝试显示一个对象列表(这里是用户,但我需要显示许多其他类型),当我尝试按照教程进行操作时,它在我的屏幕上没有显示任何内容。
而当我从 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)
有正确的邮件,但当我尝试显示它时用户仍然为空
您正在异步接收用户。所以当页面第一次呈现时,用户还没有出现。(弹出后会显示,所以他们会)
您需要为页面使用异步方法才能知道数据将在第一次渲染和重新渲染后更新。
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 文件中指定 异步管道,此道具是异步的,并且将要更新。
异步管道: https : //angular.io/api/common/AsyncPipe
可观察对象: https : //angular.io/guide/observables
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句