Angular表单提交后无法绑定API返回值至视图,求排查
Angular表单提交后无法显示返回值问题
我创建了一个Angular表单,可将值提交至WebAPI,并在提交后在表单下方打印接收到的值。
Try.component.html
<div class="container"> <form [formGroup]="form" (submit)="onSubmit()" class="mb-3"> <!-- <form class="mb-3"> --> <div class="mb-3" class="row"> <label for="bike" class="form-label fw-bold">Bike:</label> <input type="text" class="form-control" id="bike" formControlName="bike" placeholder="Enter your Bike name"> </div> <button type="submit" class="btn btn-primary mr-1">Submit</button> </form> <br> <br> <div class="table-responsive"> <table class="table table-bordered" role="grid"> <thead class="bg-primary"> <tr> <th>Bike Name</th> </tr> </thead> <tbody> <tr *ngFor="let name of names"> <td> <input type="text" [(ngModel)]="name.bike" name="bike"> </td> </tr> </tbody> </table> </div> </div>
Try.component.ts
export class TryComponent { names: any[] = []; form: FormGroup; constructor(private fb: FormBuilder, private namesService: NamesService) { this.form = this.fb.group({ bike: ['', [Validators.required, Validators.minLength(3)]] }); this.namesService.getBikes(); } Reset(){ this.form.reset(); } onSubmit() { this.form.controls['bike'].markAsTouched(); if (this.form.valid) { const data={ ...this.form.value, } console.log(data); this.namesService.addBike(data).subscribe(response => { console.log(response); this.namesService.getBikes().subscribe(names => { this.names = names; console.log(this.names); console.log("success"); }); }); } } }
Names.service.ts
export class NamesService { constructor(private http: HttpClient) { } addBike(nameData : any): Observable<any>{ return this.http.post<any[]>('https://localhost:7006/api/Names/submit-form',nameData); } getBikes(): Observable<any[]> { return this.http.get<any[]>('https://localhost:7006/api/Names/get-form-data'); } }
问题并非出在API上,因为我能在控制台打印出输入的值组成的数组(通过Swagger测试功能正常)。即便导入了必要模块,我仍无法绑定值并在表单下方显示。我推测问题出在前端数组未更新接收到的值,或是绑定方式有误。
有人能告诉我哪里出错了吗?
问题修复方案
- 构造函数中未订阅
getBikes
构造函数里调用this.namesService.getBikes()但没有订阅,初始加载时不会将数据赋值给this.names,页面自然没有初始数据。修改构造函数:
constructor(private fb: FormBuilder, private namesService: NamesService) { this.form = this.fb.group({ bike: ['', [Validators.required, Validators.minLength(3)]] }); // 订阅获取初始数据 this.namesService.getBikes().subscribe(names => { this.names = names; }); }
- 嵌套订阅导致的潜在问题
onSubmit中嵌套订阅getBikes,不仅写法不规范,还可能引发订阅泄漏。改用switchMap合并数据流:
import { switchMap } from 'rxjs/operators'; // ... onSubmit() { this.form.controls['bike'].markAsTouched(); if (this.form.valid) { const data = {...this.form.value}; console.log(data); this.namesService.addBike(data).pipe( switchMap(() => this.namesService.getBikes()) ).subscribe(names => { this.names = names; console.log(this.names); console.log("success"); this.form.reset(); // 提交成功后重置表单 }); } }
- NgModel的
name属性冲突*ngFor循环内的input使用了相同的name="bike",虽然不影响显示,但可能引发表单控件识别问题,建议改为动态名称:
<tr *ngFor="let name of names; let i = index"> <td> <input type="text" [(ngModel)]="name.bike" name="bike-{{i}}"> </td> </tr>
- 确认模块导入完整性
确保当前组件所在模块已导入ReactiveFormsModule和FormsModule(因为同时使用了响应式表单和NgModel):
import { ReactiveFormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ // ...其他模块 ReactiveFormsModule, FormsModule ] }) export class YourModule { }
内容的提问来源于stack exchange,提问作者zack
相关产品推荐
相关产品推荐

