![](/img/trans.png)
[英]Using Spring boot JPA getting data from existing oracle db
[英]Getting data from localhost using Angular and Spring Boot
我正在使用 Angular 和 Spring 引導構建 web 應用程序。 我正在嘗試從本地主機獲取數據,但我什么也沒得到。
這是來自服務器的 json 數據
這是我的服務 ts
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>
這是我單擊按鈕時遇到的錯誤
首先,您應該在p
標簽中添加一個*ngIf
,因為如果Enterprise
數組未初始化(它是async
=> API 調用),您可能會收到 null 錯誤。
此外,這是實際問題,您定義了單個 model class 引用,但不是數組,這實際上是后端返回的內容。
如果你這樣做,可能會更好:
this.enterprise = data.content
雖然this.enterprises
看起來有點像這樣:
enterprises: Enterprise[];
此外,您可能尚未在 Spring 方面實施 CORS 策略。 這是一篇很好的文章: CORS 和 Spring 。 出於測試目的,將@CrossOrigin(origins = "*")
添加到您的@RestController
class。 這對開發有好處,但在生產中你不應該這樣做,因為這將允許所有來源請求你的 API。
更多提示:
HttpClientModule
嗎?更新您的問題,告訴我它是否有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.