无法在Angular + Spring Boot项目中使用*ngFor显示元素列表。

huangapple go评论73阅读模式
英文:

Unable to display list of elements using *ngFor in Angular + Spring Boot project

问题

以下是翻译好的内容:

这是 HTML 部分:

<thead>
    <tr>
        <th scope="col">测试 ID</th>
		<th scope="col">测试名称</th>
		<th scope="col">测试开始日期</th>
		<th scope="col">测试结束日期</th>
        <th scope="col">测试持续时间(分钟)</th>
        <th scope="col">负面扣分</th>
        <th scope="col">添加问题</th> 
		<th scope="col">查看问题</th>
        <th scope="col">问题数量</th>
        <th scope="col">删除测试</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)"> 添加问题 </button></td>
        <td><button type="button" class="btn btn-info" (click)="viewQuestions(test.test_id)">查看问题</button></td>
        <td>{{test.no_of_questions}}</td> 
        <td><button type="button" class="btn btn-danger" (click)="deleteTest(test.test_id)">删除</button></td>
    </tr>
</tbody>

component.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);
}

service.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();
    }
}

这是 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]]
英文:

Here is the html part:

&lt;thead&gt;
                &lt;tr&gt;
                    &lt;th scope=&quot;col&quot;&gt;Test ID&lt;/th&gt;
					&lt;th scope=&quot;col&quot;&gt;Test Name&lt;/th&gt;
					&lt;th scope=&quot;col&quot;&gt;Test Start Date&lt;/th&gt;
					&lt;th scope=&quot;col&quot;&gt;Test End Date&lt;/th&gt;
                    &lt;th scope=&quot;col&quot;&gt;Test Duration (minutes)&lt;/th&gt;
                    &lt;th scope=&quot;col&quot;&gt;Negative Markinh&lt;/th&gt;
                    &lt;th scope=&quot;col&quot;&gt;Add Questions&lt;/th&gt; 
					&lt;th scope=&quot;col&quot;&gt;View Questions&lt;/th&gt;
                    &lt;th scope=&quot;col&quot;&gt;No of Questions&lt;/th&gt;
                    &lt;th scope=&quot;col&quot;&gt;Delete Test&lt;/th&gt;
                &lt;/tr&gt;
            &lt;/thead&gt;
            &lt;tbody&gt;
                &lt;tr *ngFor=&quot;let test of tests&quot;&gt;
                    &lt;th&gt;{{test.test_id}}&lt;/th&gt;
                    &lt;td&gt;{{test.test_name}}&lt;/td&gt;
                    &lt;td&gt;{{test.test_start_date | date:&quot;dd/MM/yyyy&quot;}}&lt;/td&gt;
                    &lt;td&gt;{{test.test_end_date | date:&quot;dd/MM/yyyy&quot;}}&lt;/td&gt;
                    &lt;td&gt;{{test.test_duration}}&lt;/td&gt;
                    &lt;td&gt;{{test.negative_marking}}&lt;/td&gt;
                    &lt;td&gt;&lt;button type=&quot;button&quot; class=&quot;btn btn-success&quot; (click)=&quot;addQuestions(test.test_id)&quot;&gt; Add Questions &lt;/button&gt;&lt;/td&gt;
                    &lt;td&gt;&lt;button type=&quot;button&quot; class=&quot;btn btn-info&quot; (click)=&quot;viewQuestions(test.test_id)&quot;&gt;View Questions&lt;/button&gt;&lt;/td&gt;
                    &lt;td&gt;{{test.no_of_questions}}&lt;/td&gt; 
                    &lt;td&gt;&lt;button type=&quot;button&quot; class=&quot;btn btn-danger&quot; (click)=&quot;deleteTest(test.test_id)&quot;&gt;Delete&lt;/button&gt;&lt;/td&gt;
                &lt;/tr&gt;

            &lt;/tbody&gt;

component.ts file

tests:any;
  
  questions:any;

  constructor(private service:TeacherPartService,
    private router:Router
    ) { }

  ngOnInit() {
    let response = this.service.viewTests();
    response.subscribe(data=&gt;{
      console.log(&#39;data=&#39;+data+&#39;\n&#39;);
      this.tests = data;
    });
    console.log(&#39;this.tests=&#39;+this.tests);

  }

service.ts file

public viewTests(){
    return this.http.get(&quot;http://localhost:8081/viewTests&quot;);
  }

the rest controller part

@GetMapping(&quot;/viewTests&quot;)
	public List&lt;Test&gt; viewAllTests(){
		System.out.println(&quot;viewTestss works&quot;);
		return (List&lt;Test&gt;)testRepo.viewTests();
	}

the query implementation part

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&lt;Test&gt; viewTests(){
		Query query = entityManager.createNativeQuery(&quot;select * from test&quot;);
		return (List&lt;Test&gt;)query.getResultList();
	}
}

无法在Angular + Spring Boot项目中使用*ngFor显示元素列表。

It correctly gets the no of entries in the list but is unable to display the results.

When I used the inbuilt JPA repository it was working fine but when I switched to my custom queries as per the requirements it doesn't seem to work.

This is the API response

[[4,&quot;second&quot;,&quot;2020-08-01&quot;,&quot;2020-09-04&quot;,0,120,true,1],[5,&quot;newTest28080116&quot;,&quot;2020-08-28&quot;,&quot;2020-09-01&quot;,4,100,false,1],[6,&quot;newTest28080118&quot;,&quot;2020-08-08&quot;,&quot;2020-09-01&quot;,0,300,true,1],[7,&quot;SCI_2808&quot;,&quot;2020-08-29&quot;,&quot;2020-09-05&quot;,0,50,true,1],[8,&quot;sampleTest&quot;,&quot;2020-08-28&quot;,&quot;2020-09-11&quot;,0,90,false,1]]

答案1

得分: 2

你得到一个数组的响应,尝试使用索引进行迭代,而不是使用键。

在此处查看示例

英文:

You are getting the response in an array and trying to iterate using keys, try to iterate using the index.

check sample here

答案2

得分: 1

从API响应中可以看出,该对象不是键值对,只是嵌套的字符串数组。您需要将对象更改为类似以下方式的ngFor。

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name = 'Angular';
  testActualObject: Test[] = [];

  test = [[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]];

  ngOnInit(){
    console.log(this.test);
    this.test.forEach(test => {
     var testActualObj = new Test();
     testActualObj.test_id = test[0];
      testActualObj.test_name = test[1];
      this.testActualObject.push(testActualObj);
    });
  }
}

export class Test {
  test_id: any;
  test_name: any;
}

您可以创建一个名为Test的类,可以操作您的数据,一旦完成,您可以使用ngFor来显示数据。

app.component.html

<div *ngFor="let actualobj of testActualObject">
  ID: {{actualobj.test_id}} <br />
  testName: {{actualobj.test_name}}
</div>

这是Stackblitz的链接

希望这解决了您的问题。

英文:

From the API response, I can say that the object is not a key-value pair and it's just nested string arrays. You need to change the object for the ngFor something like below.

app.component.ts

import { Component, OnInit } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;my-app&#39;,
  templateUrl: &#39;./app.component.html&#39;,
  styleUrls: [ &#39;./app.component.css&#39; ]
})
export class AppComponent implements OnInit {
  name = &#39;Angular&#39;;
  testActualObject: Test[] = [];

  test = [[4,&quot;second&quot;,&quot;2020-08-01&quot;,&quot;2020-09-04&quot;,0,120,true,1],[5,&quot;newTest28080116&quot;,&quot;2020-08-28&quot;,&quot;2020-09-01&quot;,4,100,false,1],[6,&quot;newTest28080118&quot;,&quot;2020-08-08&quot;,&quot;2020-09-01&quot;,0,300,true,1],[7,&quot;SCI_2808&quot;,&quot;2020-08-29&quot;,&quot;2020-09-05&quot;,0,50,true,1],[8,&quot;sampleTest&quot;,&quot;2020-08-28&quot;,&quot;2020-09-11&quot;,0,90,false,1]];

  ngOnInit(){
    console.log(this.test);
    this.test.forEach(test =&gt; {
     var testActualObj = new Test();
     testActualObj.test_id = test[0];
      testActualObj.test_name = test[1];
      this.testActualObject.push(testActualObj);
    });
  }


}

export class Test {
  test_id: any;
  test_name: any;
}

You can create a class called Test and you can manipulate your data and once it is done you can ngFor it to display the data.

app.component.html

&lt;div *ngFor=&quot;let actualobj of testActualObject&quot;&gt;
  ID: {{actualobj.test_id}} &lt;br /&gt;
  testName: {{actualobj.test_name}}
&lt;/div&gt;

Here is the Stackblitz link.

Hope this resolved your issue.

答案3

得分: 1

在你的情况下,结果返回 List<Object[]>

entityManager.createNativeQuery("select * from test")
    .getResultList()

只需在 createNativeQuery() 中添加 resultClass 参数:

entityManager.createNativeQuery("select * from test", Test.class)
    .getResultList()

这就是为什么:

当我使用内置的 JPA 存储库时,一切正常,但当我根据要求切换到我的自定义查询时,似乎不起作用。

英文:

In your case, the result returns List&lt;Object[]&gt;:

entityManager.createNativeQuery(&quot;select * from test&quot;)
    .getResultList()

just add resultClass param to createNativeQuery():

entityManager.createNativeQuery(&quot;select * from test&quot;, Test.class)
    .getResultList()

that's why:

> When I used the inbuilt JPA repository it was working fine but when I switched to my custom queries as per the requirements it doesn't seem to work

答案4

得分: 0

以下是翻译好的内容:

对于 Angular 和 Spring Boot 应用程序,请查看我的示例,并阅读我的文档

英文:

For the angular and Spring Boot application, check my sample, and read my doc.

huangapple
  • 本文由 发表于 2020年8月28日 20:43:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63634020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定