【问题标题】:Typescript global dictionary打字稿全球字典
【发布时间】:2020-09-30 17:00:46
【问题描述】:

我正在尝试用 Angular 编写一些飞镖游戏。而且我想让程序中的每个字段都分开,所以我写了这样的东西。

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

现在我想将它们存储在一个全局只读字典中

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

我可能想要另外一本关于单打、双打、三重和扇区的字典(按数字分隔),也许还有更多

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

我应该如何存储所有这些数据?我希望它从程序一开始就可用(至少是主程序)。

【问题讨论】:

    标签: angular typescript enums global global-object


    【解决方案1】:

    这里有一个可以帮助你的 stackblitz 演示:link 让我解释一下:
    您可以创建一个服务,您将在其中放置有关您的飞镖场和单打的所有内容,我将服务称为 dart-board.service.ts,DARTBOARD_FIELDS 是私有的,因此无法触及。
    之后,您可以将服务注入到要使用 dart 字段的组件中,对于我在 app.component.ts 中进行的演示:

    constructor(private dartBoardService: DartBoardService) {}
    

    现在您可以使用 getter 从服务中检索您想要的值:

    this.dartBoardFields = this.dartBoardService.getDartBoardFields()
    

    【讨论】:

    • 感谢您的回复!这实际上是我的计划。我很好奇是否还有其他(首选)方式来存储全局对象。
    • 你可以使用像 NGXS 或 NGRX 这样的商店,它们有点复杂,更适合更大的项目,因为它们往往有很多样板代码。我个人更喜欢 NGXS,因为它更容易与 Angular 一起使用。
    猜你喜欢
    • 2020-07-03
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 2012-11-28
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    相关资源
    最近更新 更多