簡體   English   中英

使用 Angular 和 Spring 引導從本地主機獲取數據

[英]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。


更多提示:

  • 確保 Angular 方面的 model 類實際上具有來自后端的所有字段。
  • 你確定你已經導入了HttpClientModule嗎?

更新您的問題,告訴我它是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM