Angular 从角度6中的函数返回true或false
我想从另一个函数中调用一个函数。我的代码如下所示: 这是我的父函数:Angular 从角度6中的函数返回true或false,angular,Angular,我想从另一个函数中调用一个函数。我的代码如下所示: 这是我的父函数: } else { if(this.checkIfCountyExists(data.convertedAddress[0].county)) { console.log('true'); } else { console.log('false'); } } checkIfCountyExists(county: String) { this.localisation
} else {
if(this.checkIfCountyExists(data.convertedAddress[0].county)) {
console.log('true');
} else {
console.log('false');
}
}
checkIfCountyExists(county: String) {
this.localisationService.checkCounty(county).subscribe(data => {
if(data.success) {
return true;
} else {
return false;
}
})
}
这是在父函数中调用的我的子函数:
} else {
if(this.checkIfCountyExists(data.convertedAddress[0].county)) {
console.log('true');
} else {
console.log('false');
}
}
checkIfCountyExists(county: String) {
this.localisationService.checkCounty(county).subscribe(data => {
if(data.success) {
return true;
} else {
return false;
}
})
}
my service为返回的数据保留一个接口,如下所示:
interface data {
success: Boolean,
convertedAddress: any
}
但是函数永远不会被正确调用,因为它每次都返回。那么我如何才能创建一个正确返回true和false的函数呢
VisualStudio说
无法测试void类型的表达式的真实性
我的错误在哪里?您的方法是异步的,因此它不会等待if语句并继续执行。这就是为什么你总是跳转到其他状态
将checkIfCountyExists
方法转换为Observable
checkIfCountyExists(county: String) {
return this.localisationService.checkCounty(county).map(data => {
if(data.success) {
return true;
} else {
return false;
}
})
}
然后
如果这个答案对你有帮助,请考虑把它标记为答案:“这是唯一可能的,当问题是20分钟:”。但我现在做到了,再次感谢你!