首页 > 解决方案 > 如何从http调用的响应中获取城市和州的值,以获取角度6中填写pin码的事件

问题描述

通过输入密码来填充城市和州的值,我编写了这段代码,它有时有效,但并不总是有效。问题 - 每次我输入一个数字时都会调用 http 服务,所以在我输入整个 6 位数字之前,它会调用 http 6 次,而对于第 5 位数字本身,它会填充州和城市的值。尽管填充了字段,但也给出了一个错误,告诉返回的响应是未定义的

组件.ts

 ngOnInit(): void {

        this.policyService.getPolicyInfo().subscribe(response => {
                    this.vehicleDetailsForm.patchValue( {'field':null} )
              })
}
onSubmitPin() {
        let formValuePin: any = {
            pincode: this.proposalDetailsForm.value.p_pin,


        }
        console.log(this.proposalDetailsForm.value.p_pin)
        this.policyService.getPinCode(formValuePin)
            .pipe()
            .subscribe(vehpin => {
                this.displayVehPin(vehpin),
                    console.log('vehpin: ', vehpin); //
                (error: any) => this.errorMessage = <any>error
            }
            )
    }

    displayVehPin(vehpin): void {
        this.vehidv = vehpin;
        console.log('vehpin: ', vehpin); //
        if (this.proposalDetailsForm) {
            console.log("you almost der...")
        }
        // the data on the form
        this.proposalDetailsForm.patchValue({
            p_state: vehpin.data.state_name,
            p_city: vehpin.data.city_name,

        });
        console.log(vehpin)
    }

HTML 代码

<div class="col-lg-4 m-form__group-sub">
                                            <mat-form-field class="example-full-width" appearance="outline">
                                                <mat-label>Pin Code</mat-label>
                     <input matInput placeholder="" formControlName="p_pin" (onChanges)="onSubmitPin()">

</mat-form-field>
                                            <label *ngIf="proposalDetailsForm.get('p_pin').errors?.required"  class="invalid-feedback">
            This Field is required.
            </label>
                        <label *ngIf="proposalDetailsForm.controls.p_pin.errors?.pattern"  class="invalid-feedback">
                                                        Should be a valid 6 digit number.
                                                    </label>
                                        </div>

标签: eventsevent-handlingangular6angular-httpclient

解决方案


推荐阅读