【问题标题】:returning true or false from a function in angular 6从角度 6 中的函数返回 true 或 false
【发布时间】:2019-01-05 08:56:24
【问题描述】:

我想从另一个函数中调用一个函数。我的代码如下所示: 这是我的父函数:

} 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;
        }
    })
}

我的服务拥有一个返回数据的接口,如下所示:

interface data {
  success: Boolean,
  convertedAddress: any
}

但是函数永远不会被正确调用,因为它返回everytime。那么如何创建一个正确返回真假的函数呢?

VisualStudio 说

无法测试 void 类型的表达式的真实性

我的错在哪里?

【问题讨论】:

    标签: angular


    【解决方案1】:

    您的方法是异步的,因此它不会等待您的 if 语句并继续执行。这就是为什么你总是跳到 else 条件。

    将您的 checkIfCountyExists 方法转换为 Observable

    checkIfCountyExists(county: String) {
        return this.localisationService.checkCounty(county).map(data => {
            if(data.success) {
                return true;
            } else {
                return false;
            }
        })
    }
    

    然后

    this.checkIfCountyExists(data.convertedAddress[0].county).Subscribe(res => {
           if(res) {
               console.log('true');
           } else {
               console.log('false');
           }
    });
    

    【讨论】:

    • 如果这个答案对你有帮助,请考虑将其标记为答案:) 问候
    • 这只有在问题出现 20 分钟时才有可能:)。但是我现在做到了,再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 2016-04-16
    • 2015-10-20
    • 1970-01-01
    • 2016-04-17
    • 2011-01-17
    相关资源
    最近更新 更多