Typescript global dictionary

562 views Asked by At

I'm trying to write some darts games in Angular. And I want to have every field separated in my program, so I wrote something like this.

export interface DartboardFieldsData{
  name: string;
  value: number;
  shortcut: string;
  multiplier: number;
}

export class DartboardField implements DartboardFieldsData{
  constructor(
    public readonly name: string,
    public readonly value: number,
    public readonly shortcut: string,
    public readonly multiplier: number){}
}

const S1 = new DartboardField('SINGLE_1', 1, 'S1', 1)
const S2 = new DartboardField('DOUBLE_1', 2, 'D1', 2)
...
const BULL = new DartboardField('BULL', 50, 'B', 2)
const MISS = new DartboardField('MISS', 0, '0', M)
// all fields

And now I want to store them in a global readonly dictionary

const DARTBOARD_FIELDS: {[shortcut: string]: DartboardFieldsData} = {
  'S1': S1,
  'D1': S2,
   //... rest of fields
};

I will probably want to have another dictioniaries for singles, doubles, triples and sectors (separated by number), maybe some more

readobly DARTBOARD_SINGLES: {[shortcut: string]: DartboardFieldsData} = {
  'S1': S1
  'S2': S2
   ...
  'S20': S20
};

How am I supposed to store all this data? I want it to be available from the start of the program (at least main one).

1

There are 1 answers

2
Elmehdi On

here is a stackblitz demo that can help you: link let me explain:
you can create a service inside which you are gonna put every thing about your dartboard fields and singles, I called the service dart-board.service.ts, DARTBOARD_FIELDS is private so it can't be touched.
after that you can inject the service into the component where you want to use your dart fields, for the demo I did so in app.component.ts:

constructor(private dartBoardService: DartBoardService) {}

now you can use a getter to retrieve the value you want from the service:

this.dartBoardFields = this.dartBoardService.getDartBoardFields()