我需要从currentAccount获取currentBalance,但收到错误:
错误错误:未捕获(在promise中(:TypeError:无法读取未定义的属性"currentAccount"。
我可以使用{{currentAccount.currentBalance}}在HTML文件上显示余额,但当我将其包含到函数中时,它会返回为未定义。如果我用一个静态数字替换balance,我的函数就可以很好地工作,只是不适用于currentBalance。
这是我在TS文件中的代码:
import { Component, OnInit, Input} from '@angular/core';
import { FormControl, FormGroup, Validators, ValidatorFn, FormBuilder, AbstractControl, ValidationErrors } from '@angular/forms';
import { ICustomerAccount } from 'src/app/customer/interfaces';
import { CustomerService } from 'src/app/customer/services/customer.service';
import { WireErrorComponent } from '../wire-error/wire-error.component';
@Component({
selector: 'app-wire-start',
templateUrl: './wire-start.component.html',
styleUrls: ['./wire-start.component.scss']
})
export class WireStartComponent implements OnInit{
@Input() currentAccount: ICustomerAccount;
currentBalance: string;
maxAmount = 1000000;
constructor(private dialog: MatDialog,
private _customerService: CustomerService,
private formBuilder: FormBuilder
) { }
wireStartForm: FormGroup = this.formBuilder.group({
purpose: new FormControl('', Validators.required),
amount: ['', [Validators.max(this.maxAmount), this.customValidatorFn]]
});
customValidatorFn(control: AbstractControl): { [key: string]: any } | null {
const amount: number = control.value;
const balance: number = Number(this.currentAccount.currentBalance);
if (balance >= amount) {
return null;
} else {
return {'amountMinError': true}
}
}
ngOnInit(): void {
this.currentAccount = this._customerService.getSelectedAccount();
}
}
因为您将currentAccount值作为组件的输入,所以绑定来自服务的值将正确返回值,但currentAccount可能有来自Input((的数据集
尝试从调用app-wire启动组件的组件(即从父组件(设置服务的currentAccount的数据,并将服务数据作为输入传递给类似的app-wire开始组件
<app-wire-start [currentAccount]="currentAccountFromService"></app-wire-start>
this
的上下文不同。尝试使用arrrow
函数,该函数将this
的context
设置为类。
customValidatorFn = (control: AbstractControl): { [key: string]: any } | null =>{
const amount: number = control.value;
const balance: number = Number(this.currentAccount.currentBalance);
if (balance >= amount) {
return null;
} else {
return {'amountMinError': true}
}
}
以下是工作示例:演示