首页 > 解决方案 > 在 Angular 10 中管理模型数据的正确方法

问题描述

假设我想创建一个简单的井字游戏,并且我有游戏板的模型。我的问题是,我应该把管理这个板的逻辑放在哪里。例如。

export class Board{
  boardString: string;
  rows: string[];
  separator: string;

  constructor(boardString: string, separator: string = '|'){
    this.boardString = boardString;
    this.separator = separator;
    this.rows = this.boardString.split('|');
  }
}
// inside model class 
atIndex(index: number): string{
    const atCol = index % this.rows.length;
    const atRow = (index - atCol) / this.rows.length;
    return this.rows[atRow][atCol];
  }

isFinished(): boolean {
  // check if game is finished
}

getRow(index): string{
 return this.rows[index]
}

对比

// or in the Service
atIndex(index: number): string{
    const atCol = index % this.boardModel.rows.length;
    const atRow = (index - atCol) / this.boardModel.rows.length;
    return this.boardModel.rows[atRow][atCol];
  }

isFinished(): boolean{
  // check if game is finished
}

getBoardRow(index): string{
  return this.boardModel.rows[index];
}

我不知道我是否说清楚了。井字游戏只是一个例子。我想知道我应该把负责管理模型属性的逻辑放在哪里?我从文档中读到所有逻辑都应该在服务内部。但对我来说,在某些情况下它更适合模型类(例如,getter)。将方法保留在模型类中是一种反模式吗?

标签: angulartypescriptmodelangular10

解决方案


说出来I read from documentation that all logic should be inside services有点误导。当然,这真的取决于逻辑在做什么,并且绝对不是所有逻辑都应该在服务中。

对于Models来说,保留一些逻辑是非常有意义的。一个很好的例子是 some Modalor Notificationclass,它会在初始化之后提供一些功能,比如close,onClose等等。想象一下,您需要通过类似的服务关闭通知notificationService.close(<notificationUniqueId)

您在示例中谈到了组件。您提出的逻辑对于组件来说非常好。我什至会说将它放入组件中是最佳实践——它将使与 UI 的集成更简洁、更简单,并且您的代码将更易于管理。

不过我确实理解你的挣扎。有时,您的 UI 逻辑可能会分布在多个组件中。但是,我仍然不会将其放入Service. 就个人而言,我尝试将服务限制为逻辑 whicha) performs some API calls或. 在我最近的项目中,我们实现了另一种我们称之为 Injectable 的类型——这个类的子集处理整个组件的重复逻辑。但它创建了另一个抽象级别,并阻止了传统服务在不需要时增长。b) formats data in some wayc) manages state and actions throughout the applicationCommonUIHandler

我相信如果你搜索Angular design patterns,你会发现很多有价值的资源。一个值得一提的例子可能是https://coryrylan.com/blog/angular-design-patterns-feature-services


推荐阅读