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

Marc El Bichon
  • 397
  • 1
  • 7
  • 24

1 Answers1

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

realappie
  • 4,656
  • 2
  • 29
  • 38
  • 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 – Marc El Bichon Dec 27 '17 at 10:31
  • The type definition of `isDisabled` is clearly wrong, otherwise the javascript debugger wouldn't be showing you a `string` How about fixing that ? :D – realappie Dec 27 '17 at 10:33
  • 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 – Marc El Bichon Dec 27 '17 at 10:34
  • @MarcElBichon For a more backwards solution that will work with the newly changed API. Check my updated answer :) – realappie Dec 27 '17 at 10:38