如何使打字稿显式评估胖箭头功能?
How to make typescript evaluate a fat arrow function explicitly?
我在 angular 中使用 FormBuilder
form.I 想要根据从 API 收到的响应初始化 FormControl
的值调用后端(此处称为 userFormDetails
)。
我正在尝试使用粗箭头函数 ()=>
来达到同样的目的:
//Other Form Controls
empCode:[this.userFormDetails.userId],
empName:[this.userFormDetails.name],
pensionType:[''],
fhName:[
()=>{
return this.userFormDetails.gender=="Male"? this.userFormDetails.fatherName:this.userFormDetails.spouseName
}],
.
//Rest of the controls
然而这被评估为
function () { return _this.userFormDetails.gender == "Male" ? _this.userFormDetails.fatherName : _this.userFormDetails.spouseName; }
它return将函数本身作为值,而不是对其求值。如何让函数 return 成为评估值?
我也试过:
1.
()=>{ ( **<--addition parenthesis**
return this.userFormDetails.gender=="Male"? this.userFormDetails.fatherName:this.userFormDetails.spouseName
)}
- 设置FormControl的值为:
fhName:[{
value: ()=>{
return this.userFormDetails.gender=="Male"?
this.userFormDetails.fatherName:this.userFormDetails.spouseName
},
disabled:false
}
]
但其中 none 有效。
有人可以指导我执行此操作的正确方法吗?
您正在将表单控件设置为等同于函数。你已经声明了它但你没有调用它,所以作为一个匿名函数用作闭包,如下所示。
试试这样改,
fhName:[(()=>{
return this.userFormDetails.gender=="Male"? this.userFormDetails.fatherName:this.userFormDetails.spouseName
})()]
()
包裹在 ()
函数末尾的额外 ()
将声明并调用该函数。
查看更多关于 anonymous function
正如@Jithin Scaria 在评论中所建议的,以下方法有效:
(() => { / content / })()
将函数包装在括号中然后调用它使 TS 计算值并 return 它。
我在 angular 中使用 FormBuilder
form.I 想要根据从 API 收到的响应初始化 FormControl
的值调用后端(此处称为 userFormDetails
)。
我正在尝试使用粗箭头函数 ()=>
来达到同样的目的:
//Other Form Controls
empCode:[this.userFormDetails.userId],
empName:[this.userFormDetails.name],
pensionType:[''],
fhName:[
()=>{
return this.userFormDetails.gender=="Male"? this.userFormDetails.fatherName:this.userFormDetails.spouseName
}],
.
//Rest of the controls
然而这被评估为
function () { return _this.userFormDetails.gender == "Male" ? _this.userFormDetails.fatherName : _this.userFormDetails.spouseName; }
它return将函数本身作为值,而不是对其求值。如何让函数 return 成为评估值?
我也试过:
1.
()=>{ ( **<--addition parenthesis**
return this.userFormDetails.gender=="Male"? this.userFormDetails.fatherName:this.userFormDetails.spouseName
)}
- 设置FormControl的值为:
fhName:[{
value: ()=>{
return this.userFormDetails.gender=="Male"?
this.userFormDetails.fatherName:this.userFormDetails.spouseName
},
disabled:false
}
]
但其中 none 有效。 有人可以指导我执行此操作的正确方法吗?
您正在将表单控件设置为等同于函数。你已经声明了它但你没有调用它,所以作为一个匿名函数用作闭包,如下所示。
试试这样改,
fhName:[(()=>{
return this.userFormDetails.gender=="Male"? this.userFormDetails.fatherName:this.userFormDetails.spouseName
})()]
()
包裹在 ()
函数末尾的额外 ()
将声明并调用该函数。
查看更多关于 anonymous function
正如@Jithin Scaria 在评论中所建议的,以下方法有效:
(() => { / content / })()
将函数包装在括号中然后调用它使 TS 计算值并 return 它。