angularangular-arrays

Angular - how to reuse a standard data array


I am using a Indian states data array like the below in various components of my Angular project.

I know one way is to add it as a collection in backend database. But I would not like to make an API call to get the state names every time a dropdown needs it.

What is the best way to define it in ONE place within angular instead of defining this constant separately in each component.

const States = [
 { name:"Assam",  code:"18",  tin:"AS" },
  { name:"Bihar",  code:"10",  tin:"BH" },
  { name:"Chandigarh",  code:"04",  tin:"CH" },
....
]

Solution

  • You could create a file, constArrays.ts somewhere near the root of your application. You can then export the constant value like so:

    // constArrays.ts
    
    export const States = [
     { name:"Assam",  code:"18",  tin:"AS" },
      { name:"Bihar",  code:"10",  tin:"BH" },
      { name:"Chandigarh",  code:"04",  tin:"CH" },
    ....
    ]
    
    

    You can then import and use this in any other file like this:

    import * as constArrays from 'path/to/file/constArrays';
    let states = constArrays.States;