0

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 Answers 3

3

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);
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks. Although I have marked the below answer as solution. I am going to try your answer too and also upvoted.
1

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;

Comments

0

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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.