redux17
redux17

Reputation: 685

Typescript boolean function must return a value

I have following Typescript boolean function:

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

The method appears error the function must return value. I know it, but I'm not sure how to implement this true/false statement outside foreach scope ?

If I call if/else statament outside foreach loop result is always false because

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

is empty..

EDIT

I've deleted checkRiskValues() function and add complete logic in ngOnInit() method and I'have also added valueControl varibable that keep true/false value and pass in another function. Thanks everyone..This my solution:

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

Upvotes: 5

Views: 52602

Answers (1)

axl-code
axl-code

Reputation: 2274

This is my proposal:

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

This way you are:

  1. Building your array
  2. Checking if exists a positive value (if true is present will return the index)

Upvotes: 4

Related Questions