Going through an archive of constants

Asked

Viewed 79 times

2

I created the following constant file (constants.ts):

export const USER_INFO = 'user-info';
export const USER_SEARCH = 'user-search';
export const USER = 'user';

This file is used to set, retrieve and delete files from localStorage:

import { USER_INFO } from '../utils/constantes';
const usuarioLogado = JSON.parse(localStorage.getItem(USER_INFO));

I need to go through the file to use all the counters in a line of code, but I do not know how to do it, because foreach is not supported in this situation. How to do?

Below is a practical example of what I wanted to accomplish:

import * as CONSTANTES_CACHE from '../utils/constantes';

export class CacheService {

  constructor() { }

  limparCache(): void {    
    CONSTANTES_CACHE.forEach(x => {
      localStorage.removeItem(x);
    });
}

2 answers

1

If you want a simple way to do this is instead of using multiple constants, leave everything in one within one array and make a for to go through the data:

const USER = ['user_info', 'user-search', 'user'];

for(let i = 0; i<USER.length; i++) {
	console.log('localStorage.removeItem ' + (USER[i]));
}

  • Good idea. I implemented it that way, because several files of my application only matter the desired constant and in my constant file there are many more than those 3 that I mentioned of example.

  • 1

    I was able to implement it as follows: cleanCache(): void { Object.Keys(CONSTANTES_CACHE). foreach(x => { localStorage.removeItem(x); }); } Thanks for the help.

-1

I was able to implement it as follows: cleanCache(): void { Object.Keys(CONSTANTES_CACHE). foreach(x => { localStorage.removeItem(x); }); }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.