【问题标题】:Getting data from localhost using Angular and Spring Boot使用 Angular 和 Spring Boot 从本地主机获取数据
【发布时间】:2020-07-23 15:24:37
【问题描述】:

我正在使用 Angular 和 Spring Boot 构建一个 Web 应用程序。我正在尝试从 localhost 获取数据,但我一无所获。

这是来自服务器的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>

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

【问题讨论】:

  • 你确定你没有使用 https 吗?
  • 不,我没有使用 https
  • 你有什么尝试调试这个问题。我看不出有什么问题。但为了调试,请使用纯 JavaScript 文件并使用如下所示的 fetch 请求: fetch("localhost:8080/entreprises/all") .then((response) => response.json()) .then((data) => console。日志(数据))

标签: java json angular spring spring-boot


【解决方案1】:

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


另外,这是实际的问题,您定义了一个模型类引用,而不是一个数组,这实际上是您的后端返回的内容。

如果你这样做可能会更好:

this.enterprise = data.content

虽然this.enterprises 看起来有点像这样:

enterprises: Enterprise[];

此外,您可能还没有在 Spring 方面实施 CORS 策略。这是一篇很好的文章:CORS with Spring。 出于测试目的,将@CrossOrigin(origins = "*") 添加到您的@RestController 类中。这对开发有好处,但在生产中你应该不要这样做,因为这将允许所有来源请求你的 API。


更多提示:

  • 确保您在 Angular 方面的模型类确实具有来自后端的所有字段。
  • 您确定已导入HttpClientModule

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

【讨论】:

  • 谢谢它的工作.. 我添加了@CrossOrigin(origins = "*") 到我的服务器,它工作
猜你喜欢
  • 2017-09-15
  • 2014-04-02
  • 2018-05-16
  • 2019-11-09
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
  • 2019-03-12
  • 2019-07-13
相关资源
最近更新 更多