【发布时间】:2021-08-01 21:57:16
【问题描述】:
所以我试图从我的后端 Python 获取数据,并且数据库在 SQLite 中,并在我的 Angular 前端。我认为我的功能正确,但是当我尝试打开页面时,它会收到以下错误消息:
ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
我对角度很陌生,所以任何可能导致此问题的帮助都会有所帮助。谢谢
这是我的 users.component.html:
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Username</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of userList">
<td>{{user.ID}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
</tr>
</tbody>
</table>
这是我的 users.component.ts:
import {Component, OnInit} from '@angular/core';
import {UserData} from "./users.model";
import {AppService} from "../app.service";
export interface UserData {
ID: number;
username: string;
email: string;
}
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {
selectedUser?: UserData;
userList: UserData[] = [];
constructor(private appService: AppService) {
}
ngOnInit() {
this.appService.getUsers().subscribe(
response=>{
this.userList=response
}
)
}
}
编辑:应 rahals 的要求。这是postman中的get方法,获取用户的json:
"results": [
{
"id": 1,
"first_name": "huh",
"email": "damn@damn.com",
"username": "damn"
},
{
"id": 2,
"first_name": "son",
"email": "damnson@me.com",
"username": "Administrator"
},
【问题讨论】:
-
您能否使用 PostMan 之类的工具提供从后端传入的数据样本
-
userList 必须是一个可迭代对象(例如数组),确保端点 USERS_URL 发出一个可迭代对象。
-
@serrulien 但 USERS_URL,这只是数据库的 url,我如何确保该部分发出一个可迭代的。 Rahal,我现在肯定会编辑它
-
只需在后端返回一组对象,而不仅仅是 1 个用户对象。您不能将不可迭代的对象分配给数组。
-
@H3AR7B3A7 如果你能详细说明一下。我该怎么办?
标签: javascript angular typescript