Angular - how to reuse a standard data array

572 views Asked by At

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" },
....
]
3

There are 3 answers

0
James Hyde On BEST ANSWER

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;
1
TotallyNewb On

I guess that the best practice would be to create a service - e.g. StatesService that would be provided either in a module or a root of the application depending on the needs. I would add a getStates() method that would return observable of the states.

This way, in case your architecture ever changes, you're prepared that your data CAN be returned asynchronously from external source and all your code would still be valid.

A sample implementation:

export class State {
  name: string;
  code: string;
  tin: string;
}

@Injectable({
  providedIn: 'root',
})
export class StatesService {
    private states: State[] = [
    { name:"Assam",  code:"18",  tin:"AS" },
     { name:"Bihar",  code:"10",  tin:"BH" },
     { name:"Chandigarh",  code:"04",  tin:"CH" },
   ];

   getStates(): Observable<State[]> {
     return of(this.states);
   }
}
0
Sanka Sanjeeva On

I think it is very easy to use and maintain with a configuration file.

states.config.json

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

then import it when need

import states from 'src/assets/states.config.json';