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

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

Getting data from localhost using Angular and Spring Boot

问题

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

这是来自服务器的JSON数据

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

这是我的服务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>

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

使用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

import { Injectable } from &#39;@angular/core&#39;;
import { HttpClient } from &#39;@angular/common/http&#39;;
import {map, catchError} from &quot;rxjs/operators&quot;;
import { Observable, throwError } from &#39;rxjs&#39;;
import {Entreprise} from &#39;../modules/entreprise&#39;;

@Injectable({
  providedIn: &#39;root&#39;
})
export class EntrepriseService {

  constructor(private http:HttpClient) {  }
 

  public getEntreprises():Observable&lt;Entreprise&gt;{

    return this.http.get&lt;Entreprise&gt;(&quot;http://localhost:8080/entreprises/all&quot;);

   		    }

}

And this is component ts:

import { Component, OnInit } from &#39;@angular/core&#39;;
import { EntrepriseService } from &#39;../services/entreprise.service&#39;;
import {Entreprise} from &#39;../modules/entreprise&#39;;


@Component({
  selector: &#39;app-login&#39;,
  templateUrl: &#39;./login.component.html&#39;,
  styleUrls: [&#39;./login.component.css&#39;]
})


export class LoginComponent implements OnInit {

entreprises:Entreprise;


  constructor(private entrepriseService:EntrepriseService) { }

  public onGetEntreprises(){

    return this.entrepriseService.getEntreprises().
   subscribe(data =&gt;{
      this.entreprises = data;

      console.log(data);
    });
      
  }

  ngOnInit(): void {


  	
  }

}

And this is the html template

&lt;h4&gt;entreprises&lt;/h4&gt;
&lt;button (click)=&quot;onGetEntreprises()&quot;&gt;get &lt;/button&gt;

&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 调用),可能会出现空错误。


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

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

this.enterprise = data.content

this.enterprises 大致如下:

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:

this.enterprise = data.content

While this.enterprises looks somewhat like this:

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:

确定