angular - 在 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)。将方法保留在模型类中是一种反模式吗?
- 内部模型类(板)
- 使用此模型的内部服务 (GameService)
- 结合以上两个
- 为该模型(BoardService)创建具有所有需要功能的服务并将其注入另一个服务(GameService)
解决方案
说出来I read from documentation that all logic should be inside services
有点误导。当然,这真的取决于逻辑在做什么,并且绝对不是所有逻辑都应该在服务中。
对于Models来说,保留一些逻辑是非常有意义的。一个很好的例子是 some Modal
or Notification
class,它会在初始化之后提供一些功能,比如close
,onClose
等等。想象一下,您需要通过类似的服务关闭通知notificationService.close(<notificationUniqueId)
。
您在示例中谈到了组件。您提出的逻辑对于组件来说非常好。我什至会说将它放入组件中是最佳实践——它将使与 UI 的集成更简洁、更简单,并且您的代码将更易于管理。
不过我确实理解你的挣扎。有时,您的 UI 逻辑可能会分布在多个组件中。但是,我仍然不会将其放入Service
. 就个人而言,我尝试将服务限制为逻辑 whicha) performs some API calls
或. 在我最近的项目中,我们实现了另一种我们称之为 Injectable 的类型——这个类的子集处理整个组件的重复逻辑。但它创建了另一个抽象级别,并阻止了传统服务在不需要时增长。b) formats data in some way
c) manages state and actions throughout the application
CommonUIHandler
我相信如果你搜索Angular design patterns
,你会发现很多有价值的资源。一个值得一提的例子可能是https://coryrylan.com/blog/angular-design-patterns-feature-services
推荐阅读
- c# - 如何在 C# 中使用带有私钥的 RS512 算法创建 JWT?
- c# - CS0104 我需要帮助 'Object' 是 'UnityEngine.Object' 和 'object' 之间的模棱两可的引用
- wamp - 我在 Wamp localhost 仪表板的“您的项目”下看不到可点击的图标
- c# - 使用 Emgu CV 将图像保存到文件夹
- python - pandas 数据帧中的 Isna() 函数返回布尔值,但它将我的数据帧转换为 NaN,为什么?
- c - 计算 Line 和 Arc 之间的交点
- recursion - 在递归函数中链接本地迭代器时出现 Rust Lifetime 问题
- c# - 检测玩家何时与粒子碰撞 - Unity
- python - Asyncpg/PostgreSQL (python/discord.py)
- android - 垂直向下滑动动画在 iOS 上不起作用