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

标签 java json angular spring spring-boot

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

这是来自服务器的json数据

enter image description here

这是我的服务

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>

这是我点击按钮时遇到的错误

enter image description here

最佳答案

首先,您应该将 *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/

相关文章:

java - Spring Controller 预处理@ModelAttribute请求参数

Jquery ajax json 获取由 Flask Web 框架传递的调用 - 调用失败

javascript - 基于 JSON 添加表行

javascript - Json语法有什么问题

typescript - 何时在 Angular2 typescript 中创建构造函数?

Angular2 - 预期的安全值必须使用 [property] = binding

java - 如何在我定义的 Java 对象中覆盖返回具有唯一实体 ID 的唯一哈希码值的哈希码方法?

java - SQL False 命令、Java 代码和 SQL?希望可以有人帮帮我

java - NSLog 与 Java 中的 System.out.print 的工作方式相同吗?

服务器上传后 Angular2 更新图像 [src]