You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 14:如何通过第三方API验证账号输入并显示客户名

实现Angular 14中账号输入时的第三方API验证与客户名展示

要实现用户输入账号时自动调用第三方API验证并显示客户姓名,按以下步骤操作:


1. 创建账号验证服务封装API请求

将HTTP请求逻辑封装到独立服务中,提升代码可维护性:

// account-validation.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class AccountValidationService {
  private apiUrl = 'https://thirtpartyapi.com/AccountDetail';

  constructor(private http: HttpClient) {}

  getAccountDetail(accountNumber: string): Observable<any> {
    const params = new HttpParams().set('accountNumber', accountNumber);
    return this.http.get(this.apiUrl, { params });
  }
}

2. 组件中监听账号输入变化(带防抖)

在组件内监听accountNumber控件的输入变化,通过防抖避免频繁请求API,同时处理验证逻辑:

// component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { MerchantService } from './merchant.service';
import { AccountValidationService } from './account-validation.service';
import { debounceTime, distinctUntilChanged, switchMap, catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-merchant-create',
  templateUrl: './merchant-create.component.html',
  styleUrls: ['./merchant-create.component.css']
})
export class MerchantCreateComponent implements OnInit {
  createMerchantForm!: FormGroup;
  isSubmitted = false;
  isLoading = false;
  customerName: string | null = null;
  accountValidationError: string | null = null;

  get fc() {
    return this.createMerchantForm.controls;
  }

  constructor(
    private fb: FormBuilder,
    private merchantService: MerchantService,
    private accountValidationService: AccountValidationService,
    private toastr: ToastrService
  ) {}

  ngOnInit(): void {
    this.createMerchant();
    this.setupAccountValidationListener();
  }

  createMerchant() {
    this.createMerchantForm = this.fb.group({
      userName: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(50), UsernameValidator.cannotContainSpace]],
      merchantName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(100)]],
      email: ['', [Validators.required, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$')]],
      accountNumber: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(50), Validators.pattern('^[0-9]*$')]],
    });
  }

  setupAccountValidationListener() {
    this.fc['accountNumber'].valueChanges.pipe(
      debounceTime(500), // 等待500ms用户停止输入再发起请求
      distinctUntilChanged(), // 仅当值真正变化时触发
      switchMap(accountNumber => {
        // 账号不符合格式时不请求API
        if (!accountNumber || this.fc['accountNumber'].invalid) {
          this.customerName = null;
          this.accountValidationError = null;
          return of(null);
        }
        this.accountValidationError = null;
        return this.accountValidationService.getAccountDetail(accountNumber).pipe(
          catchError(() => {
            this.accountValidationError = '账号验证失败,请检查账号是否正确';
            this.customerName = null;
            return of(null);
          })
        );
      })
    ).subscribe(response => {
      if (response) {
        this.customerName = response.CustomerName;
      }
    });
  }

  // 保留原有提交与关闭逻辑
  onMerchantSubmitForm() {
    this.isSubmitted = true;
    if (this.createMerchantForm.invalid) {
      return;
    }
    this.isLoading = true;
    const formData = this.createMerchantForm.value;

    this.merchantService.createMerchant(formData).subscribe({
      next: (res: any) => {
        this.toastr.success(res.message);
        this.isLoading = false;
        this.onClose();
      },
      error: (error) => {
        let errorMessage = '';
        if(error.error instanceof ErrorEvent) {
          errorMessage = error.message;
        } else {
          errorMessage = error.error.message;
        }
        this.toastr.error(errorMessage);
        this.isLoading = false;
      }
    });
  }

  onClose() {
    this.createMerchantForm.reset();
    this.customerName = null;
    this.accountValidationError = null;
    this.isSubmitted = false;
  }
}

3. 修改模板显示验证结果

在accountNumber输入框下方添加区域,展示客户姓名或验证错误:

<!-- 修改component.html中accountNumber对应的form-group -->
<div class="col-md-6">
  <div class="form-group">
    <label for="accountNumber">Account Number<span style="color:red;">*</span></label>
    <input type="text" class="form-control" formControlName='accountNumber' id="accountNumber" placeholder="Account Number">
    <!-- 原有的表单验证错误提示 -->
    <div *ngIf="fc['accountNumber'].touched && fc['accountNumber'].invalid" class="alert alert-danger">
      <div *ngIf="fc['accountNumber'].errors && fc['accountNumber'].errors['required']">Account Number is required!</div>
      <div *ngIf="fc['accountNumber'].errors && fc['accountNumber'].errors['minlength']">Account Number cannot be less than 5 characters!</div>
      <div *ngIf="fc['accountNumber'].errors && fc['accountNumber'].errors['maxlength']">Account Number cannot be more than 50 characters!</div>
      <div *ngIf="fc['accountNumber'].errors && fc['accountNumber'].errors['pattern']">Enter only numbers for Account Number!</div>
    </div>
    <!-- 新增:API验证错误提示 -->
    <div *ngIf="accountValidationError" class="alert alert-warning">
      {{ accountValidationError }}
    </div>
    <!-- 新增:客户姓名展示 -->
    <div *ngIf="customerName" class="alert alert-info">
      Customer Name: {{ customerName }}
    </div>
  </div>
</div>

注意事项

  • 确保已在AppModule中导入HttpClientModule,否则HTTP请求无法正常执行。
  • 防抖时间(500ms)可根据业务需求调整,平衡用户体验和API请求频率。
  • 可根据第三方API的实际错误返回,优化accountValidationError的提示内容。
  • 表单提交前可选择再次调用API验证账号,确保数据准确性。

内容的提问来源于stack exchange,提问作者Ayobamilaye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:15:53