为什么 API 数据在 Angular 中没有显示在正面?

Why is the API data not displayed on the front side in Angular?

提问人:thomas prevost 提问时间:9/23/2023 更新时间:9/27/2023 访问量:38

问:

我正在 Angular 和 SpringBoot 中创建一个全栈应用程序。我之前已经做过很多次这种类型的项目,但我有一个简单的问题无法解决。

这里是.ts文件:

import { Component, OnInit } from '@angular/core';
import { ChestService } from '../chest.service';
import { Chest } from '../chest.model';
import { lastValueFrom } from 'rxjs';

@Component({
  selector: 'app-chest',
  templateUrl: './chest.component.html',
  styleUrls: ['./chest.component.scss']
})
export class ChestComponent implements OnInit {

  chests: Chest[] = [];

  constructor(private chestService: ChestService) {

  }

  async ngOnInit() {
    await this.getAllChests();
    console.log(this.chests)
  }

  async getAllChests() {
    const data = await lastValueFrom(this.chestService.getAllChests());
    this.chests = data;
  }
}

这里是 .html 文件:

<h1>Mes coffres</h1>
<ng-container *ngIf="chests && chests.length > 0">
  <div *ngFor="let chest of chests">
      <p>{{ chest.name }}</p>
  </div>
</ng-container>

和模型:

export class Chest {
    id ?: number;
    name ?: string;
    description ?: string;
    creationDate ?: string;
    username ?: string;
    password ?: string;
    link ?: string;
  
    constructor(id ?: number, name ?: string, description ?: string, creationDate ?: string, username ?: string, password ?: string, link ?: string) {
      this.id = id;
      this.name = name;
      this.description = description;
      this.creationDate = creationDate;
      this.username = username;
      this.password = password;
      this.link = link;
    }
  }

当我查阅浏览器的网络选项卡时,我注意到对象是从 api 传输的。在 .ts 文件中,console.log(this.chests) 显示控制台中的对象。但是 ;html 文件只显示标签,我不明白为什么它不显示每个对象的名称。

有谁知道问题出在哪里?

HTML Angular 异步 前端

评论

0赞 Ashish Mishra 9/23/2023
你能尝试通过添加html来看到JSON吗?<pre>{{ chests | json }}</pre>
0赞 Eric Phillips 9/24/2023
我可能弄错了,但我不相信 angular 支持异步生命周期钩子
0赞 thomas prevost 9/25/2023
@AshishMishra是的,我可以看到具有良好值的 JSON!但我不明白为什么我不能以不同的方式显示它们
0赞 thomas prevost 9/25/2023
@EricPhillips这是我第一次遇到异步问题
0赞 Manish Giri 9/25/2023
您是否有指向代码的可共享链接

答:

1赞 thomas prevost 9/27/2023 #1

问题已解决:后端 objet 的字段名称与前端对象的字段名称不同。