【问题标题】:Typescript boolean function must return a value打字稿布尔函数必须返回一个值
【发布时间】:2018-07-09 20:22:55
【问题描述】:

我有以下 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 范围之外实现这个真/假语句?

如果我在 foreach 循环之外调用 if/else 语句,结果总是错误的,因为

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

是空的..

编辑

我已经删除了 checkRiskValues() 函数并在 ngOnInit() 方法中添加了完整的逻辑,并且我还添加了 valueControl 变量来保持真/假值并传入另一个函数。谢谢大家..这是我的解决方案:

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

【问题讨论】:

  • 您好,您的问题是 forEach 使用回调函数。

标签: typescript


【解决方案1】:

这是我的建议:

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. 检查是否存在正值(如果存在则返回索引)

【讨论】:

  • 所有解决方案都不起作用..我只需要最后状态这个方法(真/假)
  • 什么是返回我的方法 setRiskValues() ??
  • 这里的问题是代码通过订阅valueChanges 来填充值,这是一个可观察的。由于用户操作会发生值更改,因此在此函数运行时不会调用push,因此返回值将始终为空数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多