服务实际上从服务器获取正确的值(例如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);
}
答案 0 :(得分:0)
因为employeeService是异步函数。返回时,count将不确定。
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));
答案 1 :(得分:0)
最简单的方法:
private isDuplicateNik(nik: number): Promise<boolean>{
return this.employeeService.isDuplicateNik(nik).then(res => res > 0);
}
甚至更简单:
this.isDuplicateNik(...).then(res => {
console.log("Res: ", res);
});
然后使用它:
.bat