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

Angular中*ngFor无法渲染展示Spring Boot返回的接口数据

问题描述

Spring Boot 与 Angular 前后端连通开发场景下,通过@GetMapping配置的/getBooks接口可在Spring Boot服务端正常打印输出JSON格式的图书列表数据,但Angular端通过服务类调用接口获取数据后,无法在浏览器页面打印展示对应数据。

相关代码

Spring Boot Controller层代码

@RestController
public class BookController {
    
    @Autowired
    BookService bookservice;
        
    @GetMapping("/")
    public String homePage() {
        return "This is home Page";
    }
        
    @GetMapping("/addBook")
    public String addBook(int id, String name, String author) {
        bookservice.addBook(Book.builder().id(id).name(name).author(author).build());
        return "Book Added";
    }
        
    @GetMapping("/deleteBook")
    public String deleteBook(int id) {
        bookservice.deleteBook(id);
        return "Book deleted";
    }
        
    @GetMapping("/getBooks")
    public String getAll() {
        Gson gson = new Gson();
        String json = gson.toJson(bookservice.getAll());
        return json;
    }
}

Spring Boot Service层代码

@Service
public class BookService {
    
    @Autowired
    BookRepo repo;

    public void addBook(Book book) {
        repo.save(book);
        repo.flush();
    }
    public List<Book> getAll(){
        return repo.findAll();
    }
    public void deleteBook(int id) {
        repo.delete(Book.builder().id(id).build());
    }
}

Angular 服务类(service.ts)代码

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BookService {

  constructor(private http : HttpClient) { }

  getAll(){
    return this.http.get<any>("http://localhost:8080/getBooks");
  }
  addBook(user:any){
    return this.http.get("http://localhost:8080/addBook?id="+ user.id + "&name=" +user.name + "&author="+user.author);
  }
  deleteBook(id:any){
    return this.http.get("http://localhost:8080/deleteBook?id="+id);
  }
}

Angular 组件(appComponent.ts)代码

books:any;

constructor(private service:BookService) {}

ngOnInit():void{
  this.loadData();
}

loadData():void {
  this.service.getAll().subscribe(response => {
    this.books = response;
    console.log(this.books);
  })
}

Angular 模板(appComponent.html)代码

<p *ngFor="let temp in books">
    {{temp.name}} -- {{temp.author}}
</p>
问题原因与修复方案

该问题由两处核心错误导致,按以下步骤修改即可正常展示数据:

  • 后端接口返回值类型错误
    当前/getBooks接口手动用Gson将图书列表序列化为字符串后返回,Spring Boot会对字符串类型返回值做额外的转义包装,Angular端接收到的是纯文本字符串,而非可遍历的JSON数组,无法直接渲染。
    直接修改接口返回值为List<Book>类型即可,Spring Boot内置的序列化组件会自动完成对象到标准JSON的转换,无需手动调用Gson处理,修改后代码:
    @GetMapping("/getBooks")
    public List<Book> getAll() {
        return bookservice.getAll();
    }
    
  • Angular模板遍历语法错误
    模板中*ngFor遍历数组需要使用of关键字,当前写的in是JS遍历对象键名的语法,无法正确读取数组元素。将模板对应代码修改为:
    <p *ngFor="let temp of books">
        {{temp.name}} -- {{temp.author}}
    </p>
    
  • 跨域配置补充:如果修改后控制台报CORS跨域错误,在BookController类上添加@CrossOrigin(origins = "http://localhost:4200")注解,放行Angular本地开发端口的请求即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:54:19