You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 12调用API获取JSON后无法在HTML中渲染展示问题求助

问题根因

你定义的thesesFromWebsite变量类型和API实际返回结构不匹配,你直接将整个返回对象赋值给数组类型变量,自然无法遍历到想要的论文数据。从API返回的结构来看,真实的论文列表存放在返回对象的these字段中。

修改步骤

1. 修正component.ts代码

调整变量类型和赋值逻辑:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { TheseFromWebsite } from 'src/app/models/theseFromWebsite.model';
import { ListTheseFromWebsite } from 'src/app/models/listTheseFromWebsite.model';
import { map } from 'rxjs/operators';


@Component({
  selector: 'app-recuperation-theses-site-officiel',
  templateUrl: './recuperation-theses-site-officiel.component.html',
  styleUrls: ['./recuperation-theses-site-officiel.component.css']
})
export class RecuperationThesesSiteOfficielComponent implements OnInit {
  // 调整变量类型,直接存储论文数组
  thesesList?: TheseFromWebsite[];
  sujetRecherche='';
  

  constructor(private http: HttpClient) {
   
}
  ngOnInit(): void {
  }

  getData(): void {
    const urlThesesSite= `http://www.theses.fr/?q=${this.sujetRecherche}&fq=dateSoutenance:[1965-01-01T23:59:59Z%2BTO%2B2031-12-31T23:59:59Z]&checkedfacets=discipline=Informatique;&start=0&status=&access=&prevision=&filtrepersonne=&zone1=titreRAs&val1=&op1=AND&zone2=auteurs&val2=&op2=AND&zone3=etabSoutenances&val3=&op3=AND&zone4=dateSoutenance&val4a=&val4b=&type=&format=json`
    this.http.get<any>(urlThesesSite)
    .subscribe(
      (data)=>{
        // 提取返回对象中these字段的数组,就是目标论文列表
        this.thesesList = data.these;
        console.log(this.thesesList);   
        },    
    error => {
      console.log(error);
    });
    
  }

}

2. 修正component.html代码

现在直接遍历论文数组即可,不需要用keyvalue管道遍历整个返回对象:

<div style="text-align:center">
<h1>
  Welcome!
</h1>
<input type="text" class="form-control" [(ngModel)]="sujetRecherche">
    <button (click)="getData()" >Fetch Data</button>   
</div>

<!-- 遍历论文数组,按需取字段渲染 -->
<div *ngFor="let these of thesesList">
  <h3>论文标题:{{these.titre.fr}}</h3>
  <p>作者:{{these.auteur.nom}} {{these.auteur.prenom}}</p>
  <p>答辩日期:{{these.dateSoutenance}}</p>
  <p>所属院校:{{these.etabSoutenance.nom}}</p>
  <hr>
</div>

如果需要遍历单篇论文的所有键值对,可以在内部嵌套使用keyvalue管道:

<div *ngFor="let these of thesesList">
  <div *ngFor="let item of these | keyvalue">
    {{item.key}}: {{item.value}}
  </div>
  <hr>
</div>

注意事项

  • 本地开发时需要处理接口跨域问题,可以配置Angular代理解决,生产环境可以配置服务端跨域头或者反向代理
  • 你之前用keyvalue管道遍历整个返回对象,只能拿到第一层的键(比如these、metadata等),所以看不到论文详情,提取these数组之后遍历即可拿到每篇论文的所有字段

内容的提问来源于stack exchange,提问作者ryoune

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 01:45:03