SK.*_*SK. 0 javascript typescript angular
我试图从setTimeout()函数内部调用函数。我在下面尝试了所有方法,但还没有运气。我不确定这是Angular问题还是普通的javascript问题。如果我调用alert()函数,则它正常工作,但是当我调用函数时,它却无法正常工作。
抛出错误:this.getThreshold不是函数或不能红色属性'getThreshold'
component.ts
updateCount(inspection, rankName: string, rankPlusOrMinus: string)
{
inspection.rankName = rankName;
inspection.rankPlusOrMinus = rankPlusOrMinus;
this.inspectionService
.update(inspection).then(function(res) {
/* setTimeout(() => {
this.getThreshold(rankName, rankAcount);
});
*/
/*setTimeout(()=>{ //<<<--- using ()=> syntax
this.getThreshold();
},300);*/
/* setTimeout(function(){ // normal function
this.inspectionService.getThreshold();
}, 300) */
/* setTimeout(_=> {
//this.getThreshold();
this.inspectionService.getThreshold();
}, 300);*/
setTimeout(
function(){
this.getThreshold();
}
, 350);
})
.catch(function(rej) {
console.log(rej);
});
}
getThreshold() {
alert("123");
}
Run Code Online (Sandbox Code Playgroud)
服务
update(inspection: Inspection): Promise<Inspection> {
const url = '/api/inspection/updatecount/';
let rankName = inspection.rankName;
return this.http
.post(url, JSON.stringify(inspection), {headers: this.headers})
.toPromise()
.then(response => {
//this.alertService.success(`Successfully created associate "${associate.name}"!`, true);
let data = response.json();
if (rankName='A') inspection.rankAcount = data.rankAcount;
if (rankName='B') inspection.rankBcount = data.rankBcount;
if (rankName='C') inspection.rankCcount = data.rankCcount;
return response.json() as Inspection;
})
.catch(error => {
});
}
getThreshold() {
alert("123");
}
Run Code Online (Sandbox Code Playgroud)
在this你的函数有指当前调用上下文,而不是继承调用上下文,因为您使用的是完整的function(),而不是一个箭头的功能。请改用箭头函数,因为它们this从其父块继承其值:
this.inspectionService
.update(inspection).then((res) => {
// ...
setTimeout(() => this.getThreshold(), 350);
Run Code Online (Sandbox Code Playgroud)