我使用 Spring Boot 作為后端,使用 Angular 作為前端。我正在從 Angular 發送一個 GET 請求,以從后端資料庫中獲取 Location City 并將其保存在變數中以填充下拉串列。我使用了一個按鈕來發送請求,第一次按下按鈕時,我收到了上面標題中提到的錯誤,但是如果我第二次按下按鈕,我成功地獲取了資料。我想發送 GET 請求并在控制器中設定資料。請幫助解決錯誤,以便我可以第一次獲取資料。
Angular version: 13.3.7
Typescipt version: 4.6.4
Please check my below code:
home.component.html
目前,我已經硬編碼下拉串列中的值
<section class="vh-100 gradient-custom">
<div class="container py-5 h-100">
<div class="row justify-content-center align-items-center h-100">
<div class="col-12 col-lg-9 col-xl-7">
<div
class="card shadow-2-strong card-registration"
style="border-radius: 15px"
>
<div class="card-body p-4 p-md-5">
<h1 class="mb-4 pb-2 pb-md-0 mb-md-5 text-center">Booking Form</h1>
<hr>
<form (ngSubmit)="getBookingFormData()">
<div class="row">
<div class="col-12">
<label class="form-label select-label mx-2">From</label>
<select
class="select form-control-lg mx-5 my-5"
id="country"
[(ngModel)]="booking.from"
name="country"
>
<option *ngFor="let country of stringifiedData" [value]="country">
{{ country }}</option>
</select>
</div>
<div class="row">
<div class="col-12">
<label class="form-label select-label mx-2">To</label>
<select
class="select form-control-lg mx-5 my-2"
id="country"
[(ngModel)]="booking.to"
name="country"
>
<option value="1">Choose option</option>
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
<option value="Kolkata">Kolkata</option>
</select>
</div>
</div>
<div class="row my-4">
<div class="col-md-6 mb-4 d-flex align-items-center">
<label id="example-radio-group-label">Birth date: </label>
<div class="input-group date mx-5" data-provide="datepicker">
<input type="date" class="form-control"
[(ngModel)]="booking.date"
name="birthdayDate"
/>
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
</div>
<div class="mt-4 pt-2 ">
<button type="submit" mat-raised-button color="primary">
Book Now!</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
{{booking | json}}
home.component.ts
import { Component, OnInit } from '@angular/core';
import { LocationService } from 'src/app/service/location.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
//Variables to be used in the html file
stringifiedData: any[] = ["Mumbai", "Surat"];
Location: any;
booking = {
from !: "",
to !: "",
date !: ""
}
fetchLocation()
{
this.GetRequest.fetchLocation().subscribe(data => this.Location = data)
for (let i = 0; i < Object.keys(this.Location).length; i )
{
this.stringifiedData.push(this.Location[i].locationName);
}
console.log(this.stringifiedData);
}
getBookingFormData()
{
if(!(this.validateForm()))
{
this.fetchLocation();
}
}
validateForm()
{
if (this.booking.from == "" || this.booking.to == "" || this.booking.date == "")
{
alert("Please fill in all the fields");
return false;
}
else if (this.booking.from == this.booking.to)
{
alert("Please select different destinations");
return false;
}
else if (this.booking.date < new Date().toISOString().split('T')[0])
{
alert("Please select a future date");
return false;
}
else
{
console.log(this.booking);
return true;
}
}
constructor(private GetRequest : LocationService) {
try {
//this.fetchLocation();
} catch (error) {
console.log("Error");
}
}
ngOnInit(): void {
}
}
location.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LocationService {
private baseUrl:string = "http://localhost:8080";
constructor(private http:HttpClient) {
}
fetchLocation()
{
return this.http.get<Location[]>(`${this.baseUrl}/getLocations`);
}
}
后端:
位置控制器.java
package com.example.democom.travelbuddy.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.democom.travelbuddy.entities.LocationDO;
import com.example.democom.travelbuddy.helper.LocationService;
@RestController
@CrossOrigin
public class LocationController {
@Autowired
private LocationService locationService;
@GetMapping("/getLocations")
public ResponseEntity fetchLocation()
{
System.out.println("In LocationController");
List<LocationDO> locationDO = locationService.getLocation();
if (locationDO.size() > 0)
{
return ResponseEntity.of(Optional.of(locationDO));
}
else
//To return custome HTTPResponse
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}
LocationDO.java
package com.example.democom.travelbuddy.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class LocationDO {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "locationseq")
private Long locationId;
@Column(name = "locationname")
private String locationName;
public Long getLocationId() {
return locationId;
}
public void setLocationId(Long locationId) {
this.locationId = locationId;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
}
定位服務.java
package com.example.democom.travelbuddy.helper;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.democom.travelbuddy.dao.LocationRepository;
import com.example.democom.travelbuddy.entities.LocationDO;
@Service
public class LocationService {
@Autowired
LocationRepository locationRepository;
public List<LocationDO> getLocation() {
List<LocationDO> locationDOs = new ArrayList<>();
locationRepository.findAll().forEach(locationDOs::add);
return locationDOs;
}
}
LocationRepository.java
package com.example.democom.travelbuddy.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import com.example.democom.travelbuddy.entities.LocationDO;
@Component
public interface LocationRepository extends CrudRepository<LocationDO , Long> {
}
請檢查我在控制臺中獲得的錯誤影像的給定鏈接: 在此處輸入影像描述
uj5u.com熱心網友回復:
您必須按this.stringifiedData如下subscribe方式推動。
fetchLocation()
{
this.GetRequest.fetchLocation().subscribe(data => {
this.Location = data;
for (let i = 0; i < Object.keys(this.Location).length; i )
{
this.stringifiedData.push(this.Location[i].locationName);
}
console.log(this.stringifiedData);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/490061.html
上一篇:在jpa/hibernate中選擇新的(JPQL建構式運算式)會導致每一行的“延遲”加載
下一篇:這怎么會有回圈依賴?
