无法从数据库获取数据到 Angular

时间:2021-08-01 21:57:16

标签: javascript angular typescript

所以我试图从我的后端 Python 和数据库中获取数据到我在 Angular 中的前端。我想我的功能是正确的,但是当我尝试打开页面时,它给我这个错误信息: ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed 我对 angular 很陌生,因此任何有关可能导致此问题的帮助都会有所帮助。谢谢

这是我的 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
      }
    )
  }
}

编辑:应拉哈尔的要求。这是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"
        },

2 个答案:

答案 0 :(得分:0)

您可以从 observable 中获取更多信息,这可以帮助您找出问题所在:

#pragma

您可能希望确保您的后端返回的是某种类型的用户集合,而不仅仅是一个用户,如果是这种情况,您的问题并不清楚。

this.appService.getUsers().subscribe(
  response => { this.userList=response },
  err => console.log('HTTP Error', err),         // <-- Error handling
  () => console.log('HTTP request completed.')   // <-- Finally block
)

这看起来像一个物体。

{      // <---- Object
            "id": 4,
            "first_name": "John",
            "email": "john.doe@me.com",
            "username": "JohnD"
}

这就是对象数组的样子。

[     // <---- Array of objects
    {
            "id": 4,
            "first_name": "John",
            "email": "john.doe@me.com",
            "username": "JohnD"
    }
]

你的数组好像被包裹了,像这样。

您的 getUsers() 函数不返回 UserData[ ] 类型的 observable,而是返回类型 { results: UserData[ ] }

答案 1 :(得分:0)

我将此作为答案而不是精益评论。

根据您的问题,我没有看到 Angular 代码有任何问题。可能问题在于来自后端的数据类型。 你瘦了,你得到了一个数组 ob 对象。但是你没有得到那种类型的数据,这是不同的东西。这就是为什么 Angular 无法识别对象的属性。最好的办法是

  1. 在浏览器中打开开发者工具(按 F12)
  2. 转到网络标签
  3. 然后刷新网页
  4. 您将看到每个请求的响应数据,然后单击 您将确定问题的特定请求。
  5. 您会看到类似于 this image

6.检查您得到的响应,如果它不遵循 JSON 数组类型,那就是问题所在,您将需要从后端修复它

根据更新的问题,您应该将代码更改如下,

    ngOnInit() {
    this.appService.getUsers().subscribe(
      response=>{
        this.userList=response.results
      }
    )
  }