我正在创建一个Angular应用程序,该应用程序显示postgresql数据库中的项目列表和用户列表,但是在以html显示用户列表时遇到了问题。 问题是,无论我做什么,Angular都将我的数组视为对象。 相同的代码适用于项目,但不适用于用户。
这是我的服务
import { environment } from "../../../environments/environment";
import { Observable } from 'rxjs';
import { Projet } from '../modele/projet.model';
import { Test } from '../modele/test.model';
import { HttpParams,HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { map } from 'rxjs/operators';
import { User } from '../modele/user.model';
import { Financement } from '../modele/financement.model';
@Injectable()
export class WebService {
constructor(private httpClient: HttpClient) { }
serverUrl: string = "http://localhost:8080/"
get(url: string): Observable<any> {
return this.httpClient.get(this.serverUrl + url);
}
}
组件:
import { Component, OnInit } from '@angular/core';
import { User } from '../../shared/modele/user.model';
import { Router } from '@angular/router';
import { WebService } from '../../shared/sevices/web.service';
import { FormGroup, FormBuilder, FormControl, Validators, Form } from '@angular/forms';
@Component({
selector: 'app-show-users',
templateUrl: './show-users.component.html',
styleUrls: ['./show-users.component.scss']
})
export class ShowUsersComponent implements OnInit {
ngOnInit(): void {
this.getData();
}
usersList: Array<User>
user: User
myForm: FormGroup;
constructor(private webService: WebService, private formBuilder: FormBuilder,private router: Router) { }
getData(): void {
this.webService.get("showUsers").subscribe(res => {
let response = JSON.parse(JSON.stringify(res))
this.usersList = response.data
})
}
}
html:
<tr *ngFor="let user of usersList">
<td>{{user.name}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
</tr>
这是服务器响应: server response
注意:对象PROJECT的代码完全相同
答案 0 :(得分:1)
您需要确保传递到*ngFor
的变量是一个数组。您可以使用Array.from(v)
确保这一点,也可以使用Object.values(v)
剥离可能从服务器端发送的Object的任何键:
this.webService.get("showUsers").subscribe(res => {
this.usersList = Array.from(Object.values(res.data.body.data));
})
答案 1 :(得分:0)
您不需要此代码:
let response = JSON.parse(JSON.stringify(res))
this.usersList = response.data
只需使用:
this.userlist = res
您的完整方法:
this.webService.get("showUsers").subscribe(res => {
this.userlist = res
});