java - 无法在 Angular + Spring Boot 项目中使用 *ngFor 显示元素列表
问题描述
这是html部分:
<thead>
<tr>
<th scope="col">Test ID</th>
<th scope="col">Test Name</th>
<th scope="col">Test Start Date</th>
<th scope="col">Test End Date</th>
<th scope="col">Test Duration (minutes)</th>
<th scope="col">Negative Markinh</th>
<th scope="col">Add Questions</th>
<th scope="col">View Questions</th>
<th scope="col">No of Questions</th>
<th scope="col">Delete Test</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let test of tests">
<th>{{test.test_id}}</th>
<td>{{test.test_name}}</td>
<td>{{test.test_start_date | date:"dd/MM/yyyy"}}</td>
<td>{{test.test_end_date | date:"dd/MM/yyyy"}}</td>
<td>{{test.test_duration}}</td>
<td>{{test.negative_marking}}</td>
<td><button type="button" class="btn btn-success" (click)="addQuestions(test.test_id)"> Add Questions </button></td>
<td><button type="button" class="btn btn-info" (click)="viewQuestions(test.test_id)">View Questions</button></td>
<td>{{test.no_of_questions}}</td>
<td><button type="button" class="btn btn-danger" (click)="deleteTest(test.test_id)">Delete</button></td>
</tr>
</tbody>
组件.ts 文件
tests:any;
questions:any;
constructor(private service:TeacherPartService,
private router:Router
) { }
ngOnInit() {
let response = this.service.viewTests();
response.subscribe(data=>{
console.log('data='+data+'\n');
this.tests = data;
});
console.log('this.tests='+this.tests);
}
服务.ts 文件
public viewTests(){
return this.http.get("http://localhost:8081/viewTests");
}
其余控制器部分
@GetMapping("/viewTests")
public List<Test> viewAllTests(){
System.out.println("viewTestss works");
return (List<Test>)testRepo.viewTests();
}
查询实现部分
package com.exam.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import org.springframework.stereotype.Repository;
import com.exam.model.Test;
@Repository
public class TestRepository {
@PersistenceContext
private EntityManager entityManager;
public List<Test> viewTests(){
Query query = entityManager.createNativeQuery("select * from test");
return (List<Test>)query.getResultList();
}
}
它正确获取列表中的条目数,但无法显示结果。
当我使用内置的 JPA 存储库时,它工作正常,但是当我根据要求切换到自定义查询时,它似乎不起作用。
这是 API 响应
[[4,"second","2020-08-01","2020-09-04",0,120,true,1],[5,"newTest28080116","2020-08-28","2020-09-01",4,100,false,1],[6,"newTest28080118","2020-08-08","2020-09-01",0,300,true,1],[7,"SCI_2808","2020-08-29","2020-09-05",0,50,true,1],[8,"sampleTest","2020-08-28","2020-09-11",0,90,false,1]]
解决方案
您正在数组中获取响应并尝试使用键进行迭代,尝试使用索引进行迭代。
推荐阅读
- java - 我无法从 A2DP 移动设备发送元数据,但 Google Play 音乐如何将元数据发送到该设备?
- ember.js - 如何在 ember.js v3.8 中渲染子组件?
- c++ - 有没有办法避免这个函数中的分支/条件逻辑?
- c++ - 如何解决头文件中的变量冲突?
- c++11 - 在被调用的构造函数中使用递归
- php - 如果值位于由另一个表组成的数组中,如何使用 PHP 和 PDO 在 MySQL 中更快地插入多行(~70k)?
- javascript - 如果他没有从选择框-PHP 中选择值,如何限制用户提交表单
- verilog - 以不同的时钟将数据写入内存
- bixby - 如何使用 Bixby 视图创建水平跨越单元格?
- treemap - 在 highcharter 包 R 中使用 hctreemap2 函数时如何将 hc_plotOptions() 指定到特定层(级别)