使用Angular和Spring Boot从本地主机获取数据

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

Getting data from localhost using Angular and Spring Boot

问题

我正在使用Angular和Spring Boot构建Web应用程序。我尝试从本地主机获取数据,但是我什么都没有得到。

这是来自服务器的JSON数据

使用Angular和Spring Boot从本地主机获取数据

这是我的服务TS

  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. import { map, catchError } from "rxjs/operators";
  4. import { Observable, throwError } from 'rxjs';
  5. import { Entreprise } from '../modules/entreprise';
  6. @Injectable({
  7. providedIn: 'root'
  8. })
  9. export class EntrepriseService {
  10. constructor(private http: HttpClient) { }
  11. public getEntreprises(): Observable<Entreprise> {
  12. return this.http.get<Entreprise>("http://localhost:8080/entreprises/all");
  13. }
  14. }

这是组件TS

  1. import { Component, OnInit } from '@angular/core';
  2. import { EntrepriseService } from '../services/entreprise.service';
  3. import { Entreprise } from '../modules/entreprise';
  4. @Component({
  5. selector: 'app-login',
  6. templateUrl: './login.component.html',
  7. styleUrls: ['./login.component.css']
  8. })
  9. export class LoginComponent implements OnInit {
  10. entreprises: Entreprise;
  11. constructor(private entrepriseService: EntrepriseService) { }
  12. public onGetEntreprises() {
  13. return this.entrepriseService.getEntreprises().
  14. subscribe(data => {
  15. this.entreprises = data;
  16. console.log(data);
  17. });
  18. }
  19. ngOnInit(): void {
  20. }
  21. }

这是HTML模板

  1. <h4>entreprises</h4>
  2. <button (click)="onGetEntreprises()">get </button>
  3. <p *ngFor="let ee of entreprises">{{ee.content.name}}</p>

当我点击按钮时,我得到以下错误:

使用Angular和Spring Boot从本地主机获取数据

英文:

I'm working on build an web app using Angular and Spring Boot. I am trying to get data from localhost but I get nothing.

This is the json data from the server

使用Angular和Spring Boot从本地主机获取数据

And this my service ts

  1. import { Injectable } from &#39;@angular/core&#39;;
  2. import { HttpClient } from &#39;@angular/common/http&#39;;
  3. import {map, catchError} from &quot;rxjs/operators&quot;;
  4. import { Observable, throwError } from &#39;rxjs&#39;;
  5. import {Entreprise} from &#39;../modules/entreprise&#39;;
  6. @Injectable({
  7. providedIn: &#39;root&#39;
  8. })
  9. export class EntrepriseService {
  10. constructor(private http:HttpClient) { }
  11. public getEntreprises():Observable&lt;Entreprise&gt;{
  12. return this.http.get&lt;Entreprise&gt;(&quot;http://localhost:8080/entreprises/all&quot;);
  13. }
  14. }

And this is component ts:

  1. import { Component, OnInit } from &#39;@angular/core&#39;;
  2. import { EntrepriseService } from &#39;../services/entreprise.service&#39;;
  3. import {Entreprise} from &#39;../modules/entreprise&#39;;
  4. @Component({
  5. selector: &#39;app-login&#39;,
  6. templateUrl: &#39;./login.component.html&#39;,
  7. styleUrls: [&#39;./login.component.css&#39;]
  8. })
  9. export class LoginComponent implements OnInit {
  10. entreprises:Entreprise;
  11. constructor(private entrepriseService:EntrepriseService) { }
  12. public onGetEntreprises(){
  13. return this.entrepriseService.getEntreprises().
  14. subscribe(data =&gt;{
  15. this.entreprises = data;
  16. console.log(data);
  17. });
  18. }
  19. ngOnInit(): void {
  20. }
  21. }

And this is the html template

  1. &lt;h4&gt;entreprises&lt;/h4&gt;
  2. &lt;button (click)=&quot;onGetEntreprises()&quot;&gt;get &lt;/button&gt;
  3. &lt;p *ngFor=&quot;let ee of entreprises&quot;&gt;{{ee.content.name}}&lt;/p&gt;

And this is the error I get when I click on the button

使用Angular和Spring Boot从本地主机获取数据

答案1

得分: 1

首先,您应该在您的 p 标签上添加 *ngIf,因为如果 Enterprise 数组未初始化(它是 async => API 调用),可能会出现空错误。


此外,这才是实际的问题,您定义了一个单独的模型类引用,但没有定义一个数组,而实际上后端返回的就是一个数组。

也许,如果您这样做会更好:

  1. this.enterprise = data.content

this.enterprises 大致如下:

  1. enterprises: Enterprise[];

此外,您可能尚未在 Spring 部分实现 CORS 策略。这里有一篇关于此的好文章:CORS with Spring
为了测试目的,在您的 @RestController 类中添加 @CrossOrigin(origins = &quot;*&quot;)。这在开发时很有用,但在生产中,绝对不应这样做,因为这将允许所有来源请求您的 API。


更多提示:

  • 请确保您在 Angular 部分的模型类实际上具有来自后端的所有字段。
  • 您确定已经导入了 HttpClientModule 吗?

更新您的问题,告诉我是否有效。

英文:

First of, you should add an *ngIf to your p tag, since you could get null errors if the array of Enterprise is not initialized (it is async => API call).


Also, this is the actual problem, you defined a single model class reference, but not an array, which is actually what gets returned by your backend.

Probably, it would be better practice if you did this:

  1. this.enterprise = data.content

While this.enterprises looks somewhat like this:

  1. enterprises: Enterprise[];

Furthermore, you probably have not implemented a CORS policy on the Spring side of things. Here is a good article about that: CORS with Spring.
For testing purposes, add @CrossOrigin(origins = &quot;*&quot;) to your @RestController class. This is good for development, but in production you should defo don't do this, since this would allow all origins to request your API.


More tips:

  • Be sure that your model classes on the Angular side of things do actually have all fields which come from the backend.
  • Are you sure that you have imported the HttpClientModule?

Update your question to tell me if it works.

huangapple
  • 本文由 发表于 2020年4月11日 03:54:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/61147739.html
匿名

发表评论

匿名网友

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

确定