我正在使用 Angular 和 Spring Boot 构建一个 Web 应用程序。我试图从本地主机获取数据,但我什么也没得到。
这是来自服务器的json数据
这是我的服务
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {map, catchError} from "rxjs/operators";
import { Observable, throwError } from 'rxjs';
import {Entreprise} from '../modules/entreprise';
@Injectable({
providedIn: 'root'
})
export class EntrepriseService {
constructor(private http:HttpClient) { }
public getEntreprises():Observable<Entreprise>{
return this.http.get<Entreprise>("http://localhost:8080/entreprises/all");
}
}
这是组件 ts:
import { Component, OnInit } from '@angular/core';
import { EntrepriseService } from '../services/entreprise.service';
import {Entreprise} from '../modules/entreprise';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
entreprises:Entreprise;
constructor(private entrepriseService:EntrepriseService) { }
public onGetEntreprises(){
return this.entrepriseService.getEntreprises().
subscribe(data =>{
this.entreprises = data;
console.log(data);
});
}
ngOnInit(): void {
}
}
这是html 模板
<h4>entreprises</h4>
<button (click)="onGetEntreprises()">get </button>
<p *ngFor="let ee of entreprises">{{ee.content.name}}</p>
这是我点击按钮时遇到的错误
最佳答案
首先,您应该将 *ngIf
添加到 p
标记中,因为如果 Enterprise
数组为未初始化(它是async
=> API 调用)。
此外,这是实际的问题,您定义了单个模型类引用,而不是数组,这实际上是后端返回的内容。
如果您这样做,可能会更好:
this.enterprise = data.content
虽然 this.enterprises
看起来有点像这样:
enterprises: Enterprise[];
<小时/>
此外,您可能还没有在 Spring 方面实现 CORS 策略。这是一篇关于此的好文章:CORS with Spring 。
出于测试目的,请将 @CrossOrigin(origins = "*")
添加到您的 @RestController
类中。这对开发很有好处,但在生产中您绝对不应该这样做,因为这将允许所有来源请求您的 API。
更多提示:
- 确保 Angular 方面的模型类确实具有来自后端的所有字段。
- 您确定已导入
HttpClientModule
吗?
更新您的问题以告诉我它是否有效。
关于java - 使用 Angular 和 Spring Boot 从本地主机获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61147739/