如何将Angular前端数据传递到Spring Boot后端并接收返回结果
Angular对接Spring Boot接口完整实现步骤
1. 修正现有代码错误并完善服务层
你现有代码中this.http.get<convert[]>.后面多了一个多余的点号,先删掉修正。另外需要先完成服务的基础配置:
- 确保
app.module.ts中导入HttpClientModule,否则Http请求无法正常工作:
// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { ReactiveFormsModule } from '@angular/forms'; // 后续做表单要用到 import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, HttpClientModule, ReactiveFormsModule], bootstrap: [AppComponent] }) export class AppModule { }
- 定义和后端返回字段匹配的
Convert类型,完善服务代码:
// convert.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; export interface Convert { // 字段和后端返回的JSON字段保持一致即可,以下为示例 convertedAmount: number; targetCurrency: string; originalAmount: number; } @Injectable({ providedIn: 'root' }) export class ConvertService { constructor(private http: HttpClient) {} retrieveData(currency:string, amount: number): Observable<Convert[]> { return this.http.get<Convert[]>(`http://localhost:8080/convert/${currency}/${amount}`); } }
2. 处理跨域问题
Angular默认启动端口是4200,Spring Boot端口是8080,浏览器会拦截跨域请求,二选一处理即可:
- 方案1:在Spring Boot对应的接口类/方法上加上注解
@CrossOrigin(origins = "http://localhost:4200") - 方案2:配置Angular本地开发代理
3. 编写组件逻辑接收参数、调用接口
在你需要用到这个功能的组件中,注入服务,用响应式表单接收用户输入,绑定提交事件调用接口:
// convert.component.ts import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ConvertService, Convert } from './convert.service'; @Component({ selector: 'app-convert', templateUrl: './convert.component.html' }) export class ConvertComponent { convertForm: FormGroup; result?: Convert[]; errorMsg = ''; constructor( private fb: FormBuilder, private convertService: ConvertService ) { // 初始化表单,加校验规则 this.convertForm = this.fb.group({ currency: ['', Validators.required], amount: [0, [Validators.required, Validators.min(0.01)]] }); } onSubmit() { if (!this.convertForm.valid) return; const { currency, amount } = this.convertForm.value; // 调用服务方法订阅返回结果 this.convertService.retrieveData(currency, amount).subscribe({ next: (res) => { this.result = res; this.errorMsg = ''; }, error: () => { this.errorMsg = '请求失败,请检查参数或后端服务是否正常运行'; this.result = undefined; } }); } }
4. 编写页面模板实现交互和结果展示
在组件对应的HTML文件中编写表单和结果展示区域:
<!-- convert.component.html --> <form [formGroup]="convertForm" (ngSubmit)="onSubmit()"> <div> <label>目标货币:</label> <input formControlName="currency" type="text" placeholder="比如USD"> <span *ngIf="convertForm.get('currency')?.invalid && convertForm.get('currency')?.touched" style="color:red"> 请输入货币类型 </span> </div> <div> <label>兑换金额:</label> <input formControlName="amount" type="number" step="0.01" placeholder="请输入金额"> <span *ngIf="convertForm.get('amount')?.invalid && convertForm.get('amount')?.touched" style="color:red"> 请输入大于0的有效金额 </span> </div> <button type="submit" [disabled]="!convertForm.valid">提交计算</button> </form> <!-- 结果展示区域 --> <div *ngIf="result" style="margin-top: 20px; padding: 10px; border: 1px solid #eee;"> <h3>计算结果:</h3> <!-- 根据实际返回字段调整展示内容,以下为示例 --> <p>兑换后金额:{{result[0].convertedAmount}} {{result[0].targetCurrency}}</p> </div> <!-- 错误提示 --> <div *ngIf="errorMsg" style="color: red; margin-top: 10px;"> {{errorMsg}} </div>
内容的提问来源于stack exchange,提问作者joe
相关产品推荐
相关产品推荐

