返回 lambda 函数的函数 - lambda 函数从哪里获取其输入?



谁能解释一下下面的lambda函数?

此函数应将"mismatchedFields"设置为true/false,并将其作为对象返回,如果表单的field1field2具有相同的值:

function matchingFields(field1, field2) {
return form => {
if(form.controls[field1].value !== form.controls[field2].value)
return { mismatchedFields: true }
}   
}

它用于 Angular 表单验证器,如下所示:

export class NewUserComponent {
private form: any;
constructor(private fb: FormBuilder) {
this.form = fb.group({
password: '',
passwordConfirm: ''
}, { validator: matchingFields('password', 'passwordConfirm')})
}
}

我不明白'matchingFields'在哪里向第一个'return'返回的 lambda 函数提供变量'form'

谁能解释一下这个lambda函数的功能?

谢谢。

当你设置这个

validator: matchingFields('password', 'passwordConfirm')

你调用函数matchingFields,它从中返回另一个函数(箭头/lambda 函数)。在此调用之后,您可以认为您有一个从matchingFields返回的类似函数。

function someFunction(form) {
var field1 = 'password';
var field2 = 'passwordConfirm';
if(form.controls[field1].value !== form.controls[field2].value)
return { mismatchedFields: true }
}

formGroup现在你会有类似的东西

validator: someFunction

您刚刚将validator的引用设置为函数someFunction,这是从matchingFields返回的引用。现在,Angular将在验证阶段自动调用此函数,并且form参数将自动传递给该函数。此form是运行验证的。

FormBuilder

调用回调(即内部)。

matchingFields定义只是它的通用版本:

…
constructor(private fb: FormBuilder) {
this.form = fb.group({
password: '',
passwordConfirm: ''
}, {
validator: form => {
if (form.controls['password'].value !== form.controls['passwordConfirm'].value) {
return { mismatchedFields: true }
}
}
})
}

所以我会想象在里面FormBuilder.group(a, b)发生以下情况:

b.validator(this.internalFormReference)

下面是如何调用它的运行示例:

// The function from the question
function matchingFields(field1, field2) {
return form => {
if (form.controls[field1].value !== form.controls[field2].value)
return {
mismatchedFields: true
}
}
}
// A simplified version of the FormGroup object
const form = {
	controls: {
		a: {
			value: 'test'
		},
		b: {
			value: 'test2'
		}
	}
};
// as form.a.value !== form.b.value the validator should not be undefined
console.log(matchingFields('a', 'b')(form));

最新更新