How to convert string to boolean in typescript Angular 4

后端 未结 5 821
后悔当初
后悔当初 2021-01-31 13:33

I know am not the first to ask this and as I mentioned in my title ,I am trying to convert string value boolean .

I have previously put some values into local storage,No

5条回答
  •  遇见更好的自我
    2021-01-31 13:45

    In your scenario, converting a string to a boolean can be done via something like someString === 'true' (as was already answered).

    However, let me try to address your main issue: dealing with the local storage.

    The local storage only supports strings as values; a good way of using it would thus be to always serialise your data as a string before storing it in the storage, and reversing the process when fetching it.

    A possibly decent format for serialising your data in is JSON, since it is very easy to deal with in JavaScript.

    The following functions could thus be used to interact with local storage, provided that your data can be serialised into JSON.

    function setItemInStorage(key, item) {
      localStorage.setItem(key, JSON.stringify(item));
    }
    
    function getItemFromStorage(key) {
      return JSON.parse(localStorage.getItem(key));
    }
    

    Your example could then be rewritten as:

    setItemInStorage('CheckOutPageReload', [this.btnLoginNumOne, this.btnLoginEdit]);
    

    And:

    if (getItemFromStorage('CheckOutPageReload')) {
      const pageLoadParams = getItemFromStorage('CheckOutPageReload');
      this.btnLoginNumOne = pageLoadParams[0];
      this.btnLoginEdit = pageLoadParams[1];
    }
    

提交回复
热议问题