此方法总是返回一个未定义的值
服务实际上从服务器获得正确的值(例如1或0),但在组件中实现服务时总是返回未定义的值。我认为return
声明刚好在.then()
编译之前编译。我该如何解决这个问题?此方法总是返回一个未定义的值
private isDuplicateNik(nik: number): boolean{
let count: number;
this.employeeService.isDuplicateNik(nik).then(
res => {
count = res;
}
);
return (count > 0 ? false : true);
}
最简单的方法:
private isDuplicateNik(nik: number): Promise<boolean>{
return this.employeeService.isDuplicateNik(nik).then(res => res < 0 ? false : true);
}
而且更简单:
private isDuplicateNik(nik: number): Promise<boolean>{
return this.employeeService.isDuplicateNik(nik).then(res => res > 0);
}
然后你使用它像:
this.isDuplicateNik(...).then(res => {
console.log("Res: ", res);
});
不幸的是,我仍然得到一个未定义的输入 –
也返回了一个错误'类型无形
我已经更新了答案(类型不匹配)。你确定this.employeeService.isDuplicateNik(nik)返回一个承诺吗?尝试通过执行以下操作登录您所得到的内容: this.employeeService.isDuplicateNik(nik).then(res => console.log(res)); – Faly
因为employeeService是一个异步函数。计数将返回时不确定。
private isDuplicateNik(nik: number) {
let subject = Subject();
this.employeeService.isDuplicateNik(nik).then(
res => {
subject.next(res > 0 ? false : true);
}
);
return subject;
}
用作:
this.isDuplicateNik.subscribe(res => console.log(res));
返回错误'通用类型主题
对不起,我没有看到你给函数返回类型。只要删除它。 – Carsten
[承诺后的返回值]的可能重复(https://*.com/questions/22951208/return-value-after-a-promise) – jonrsharpe