我在一個學校專案中作業。前端正在與 API 通信,結果顯示在瀏覽器控制臺中:
console.log 中顯示的結果
這是界面
export interface Anuncios {
id: number;
AnuncioTipo: string;
AnuncioAssunto: string;
AnuncioDescricao: string;}
這是 ts 檔案:
import { Component, OnInit } from '@angular/core';
import { AnunciosService } from '../../services/anuncios.service';
import { Anuncios } from '../../interfaces/anuncios';
@Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {
anuncios: Anuncios[] = [];
constructor(public anunciosService: AnunciosService) { }
ngOnInit(): void {
this.anunciosService.getAll().subscribe((data: Anuncios[]) => {
this.anuncios = data;
console.log(this.anuncios);
});
}
}
這是html檔案:
<div class="container-fluid">
<h1>Todos os anuncios</h1>
<a href="#" routerLink="/anuncios/create" class="btn btn-sucess">Criar novo anuncio</a>
</div>
<div>
<ng-container *ngFor="let anuncio of anuncios">
<p>ID: {{ anuncio.id }}</p>
<p>Tipo: {{ anuncio.AnuncioTipo }}</p>
<p>Assunto: {{ anuncio.AnuncioAssunto }}</p>
<p>Descri??o: {{ anuncio.AnuncioDescricao }}</p>
</ng-container>
</div>
結果顯示在應用程式中,它只顯示ID
該應用程式沒有顯示從 Web API 收集的資料,我該如何解決這個問題?
uj5u.com熱心網友回復:
螢屏截圖中的 API 結果顯示物件鍵在camelCase中,但您的界面在TitleCase中有它們。
如果這不能解決問題,那么其他幾個問題可能是 -
- API 拋出錯誤,因此
catchError(this.errorHandler)內部getAll()方法回傳一個空陣列。 - 組件或父組件的
ChangeDetectionStrategy設定為OnPush。雖然它不應該在這里創建這個特定的問題,但你永遠不會知道。
首先檢查方法是否有錯誤AnunciosService.getAll()。如果沒有,那么您可以嘗試使用async管道。這樣您就可以克服更改檢測并自動關閉流以防止可能的記憶體泄漏。
import { Component } from '@angular/core';
import { AnunciosService } from '../../services/anuncios.service';
import { Anuncios } from '../../interfaces/anuncios';
import { Observable } from 'rxjs';
@Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.css']
})
export class IndexComponent {
anuncios$: Observable<Anuncios[]> = this.anunciosService.getAll();
constructor(public anunciosService: AnunciosService) { }
}
模板:
<div>
<ng-container *ngFor="let anuncio of anuncios$ | async"> <!-- use async -->
<p>ID: {{ anuncio.id }}</p>
<p>Tipo: {{ anuncio.AnuncioTipo }}</p>
<p>Assunto: {{ anuncio.AnuncioAssunto }}</p>
<p>Descri??o: {{ anuncio.AnuncioDescricao }}</p>
</ng-container>
</div>
uj5u.com熱心網友回復:
您的介面屬性(在這種情況下)需要與來自 API 的屬性相匹配,它們都以 API 中的小寫字母 (camelCase) 開頭,如控制臺日志中所示。
嘗試將您的界面更改為此
export interface Anuncios {
id: number;
anuncioTipo: string;
anuncioAssunto: string;
anuncioDescricao: string;
}
和你的 html 到這個
<ng-container *ngFor="let anuncio of anuncios">
<p>ID: {{ anuncio.id }}</p>
<p>Tipo: {{ anuncio.anuncioTipo }}</p>
<p>Assunto: {{ anuncio.anuncioAssunto }}</p>
<p>Descri??o: {{ anuncio.anuncioDescricao }}</p>
</ng-container>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/497431.html
標籤:javascript html 有角度的
