Angular如何实现输入PIN CODE自动填充省市区地址功能
问题原因
- HttpClient实例名错误:构造函数注入的是
httpClient,但调用get请求时写的是this.http,会直接报错找不到http对象 - API返回结构问题:
https://api.postalpincode.in/pincode/xxx返回的是数组,数组第一个元素才是包含Message、PostOffice字段的对象,直接访问finalAddress.Message肯定拿不到值 - 初始化问题:
finalAddress初始值是undefined,接口未返回之前模板渲染就会报访问属性的错误 - 多余的序列化反序列化操作:HttpClient的get请求默认已经把返回的JSON转成JS对象,额外的JSON.stringify+JSON.parse完全是无效操作
- 输入框没有绑定ngModel:拿到地址数据之后无法自动填充到对应的输入框中
修复后的代码
1. component.ts 代码
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-final-pay', templateUrl: './final-pay.component.html', styleUrls: ['./final-pay.component.css'] }) export class FinalPayComponent implements OnInit { public pinCode = ''; // 单独声明地址字段变量,方便直接绑定模板 public state = ''; public district = ''; public city = ''; constructor( private httpClient: HttpClient ) { } ngOnInit(): void { } getAdd(pinCode: string){ // 先判断pin码长度符合要求再发起请求,避免无效请求 if(pinCode.length !== 6) return; // 使用正确注入的httpClient实例发起请求 this.httpClient.get(`https://api.postalpincode.in/pincode/${pinCode}`).subscribe((res: any)=>{ // 先判断接口返回成功再赋值 if(res && res[0]?.Status === 'Success') { const postOfficeInfo = res[0].PostOffice[0]; this.state = postOfficeInfo.State; this.district = postOfficeInfo.District; this.city = postOfficeInfo.Name; } else { alert('输入的PIN码无效,请检查'); // 清空之前的地址数据 this.state = ''; this.district = ''; this.city = ''; } }); } }
2. HTML 模板代码
<div class="cardParts5"> <div class="cardTitle"> Communication Address </div> <div class="addressContainer"> <div class="field1"> <mat-form-field class="example-full-width mat-form" appearance="fill"> <mat-label>Pin Code*</mat-label> <input matInput maxlength="6" [(ngModel)]="pinCode" name="pinCode"> <button (click)="getAdd(pinCode)">查询地址</button> </mat-form-field> </div> <div class="field2"> <mat-form-field class="example-full-width mat-form" appearance="fill"> <mat-label>State*</mat-label> <input matInput [(ngModel)]="state" name="state"> </mat-form-field> </div> <div class="field3"> <mat-form-field class="example-full-width mat-form" appearance="fill"> <mat-label>District*</mat-label> <input matInput [(ngModel)]="district" name="district"> </mat-form-field> </div> <div class="field4"> <mat-form-field class="example-full-width mat-form" appearance="fill"> <mat-label>City/Village*</mat-label> <input matInput [(ngModel)]="city" name="city"> </mat-form-field> </div> </div> </div>
额外优化建议
- 可以给pin码输入框加
(blur)事件,用户输完离开输入框自动触发查询,不用手动点击按钮 - 记得在对应的模块里导入
HttpClientModule和FormsModule,否则ngModel和http请求都会报错 - 可以加上请求loading状态,避免用户重复点击按钮
内容的提问来源于stack exchange,提问作者Anonymous
相关产品推荐
相关产品推荐

