0

I'm facing a strange issue while filling a model from a API result.

My model looks like this:

import {Company} from './../api/odata/data/Company';

export class MyModel {
...
isEnabled = false;
....
    constructor(data: Company= null) {
        try {
            this.isEnabled = !data.isDisabled;
            ...
        }
        ...
}

When I fill the data model, if data.isDisabled equals false, this.isEnabled should be true, but it's returning false...

enter image description here

enter image description here

1 Answer 1

3

data.isDisabled is a string buddy. You could convert it to a boolean in multiple ways. But I am curious where the data came from in the first place.

If there is no way to ensure data.isDisabled comes as a boolean you could do two things.

1- Check what the strings value is and based on that return a boolean.

this.isEnabled = data.isDisabled === 'true' ? false : true

2- Or use eval, which I would not recommend

this.isEnabled = eval(data.isDisabled);

3- Backwards compatible solution, best of all three

This will even work if isDisabled is an actual boolean.

this.isEnabled = !JSON.parse(data.isDisabled);

See more on string to boolean conversion here

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help, but i get a "Operator '===' cannot be applied to types 'boolean' and '"true"'." when i try your first solution, and in the Company oData class, isDisabled is declared as boolean
The type definition of isDisabled is clearly wrong, otherwise the javascript debugger wouldn't be showing you a string How about fixing that ? :D
thanks, after changing it, it fixed the issue, I will ask the API dev to change this, it's not normal to return a string for a boolean value
@MarcElBichon For a more backwards solution that will work with the newly changed API. Check my updated answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.