Typescript布尔函数必须返回一个值

时间:2018-01-30 20:34:19

标签: typescript

我有以下的Typescript布尔函数:

checkRiskValues(): boolean {
    this.controlsName.forEach((item) => {
        this.threatForm.get(item)!.valueChanges.subscribe(value => {
            this.valueControlArray.push(this.threatForm.get(item)!.value);

            if (this.valueControlArray.indexOf(true) > -1)
                return true;

            else
                return false
        });
    });
}

方法出现错误,函数必须返回值。我知道,但我不确定如何在foreach范围之外实现这个真/假声明?

如果我调用if / else在foreach循环结果之外的statament总是假的,因为

if (this.valueControlArray.indexOf(true) > -1)

是空的..

修改

我删除了checkRiskValues()函数并在ngOnInit()方法中添加了完整的逻辑,我还添加了valueControl varibable,它保持true / false值并传入另一个函数。谢谢大家......这是我的解决方案:

ngOnInit() {
    this.controlsName.forEach((item) => {
        this.threatForm.get(item)!.valueChanges.subscribe(value => {
            this.valueControlArray.push(this.threatForm.get(item)!.value);

            if (this.valueControlArray.indexOf(true) > -1) {
                this.valueControl = true;

            }
            else {
                this.valueControl = false;
            }
        });
    });
}

1 个答案:

答案 0 :(得分:2)

这是我的建议:

checkRiskValues(): boolean {
    return setRiskValues().indexOf(true) > -1;
}

setRiskValues(): Array<any> {
    let values = [];
    this.controlsName.forEach((item) => {
        this.threatForm.get(item)!.valueChanges.subscribe(value => {
            values.push(this.threatForm.get(item)!.value);
        });
    });

    return values;
}

这样你就是:

  1. 构建阵列
  2. 检查是否存在正值(如果存在,则返回索引)
相关问题