angular - 有没有办法通过将服务注入/导入到不是组件/服务/存储库的类中来提高代码质量?
问题描述
在此示例中,我将使用 2 个文件( LogService 和 LoggedConflictException )。
我想将 LogService 注入到 LoggedConflictException 类中,而不是通过 LoggedConflictException 的构造函数或方法传递它。这就是我现在所做的(我一点也不喜欢):
export class LoggedConflictException extends ConflictException {
constructor( logService: LogService, options?: {
purpose?: string,
credentials?: any,
message?: string | object | any,
error?: string
} ) {
super( options.message );
// the fact that I have to pass logService instance every time does make me worry.
// I would like to inject logService directly without the need to pass it down from other classes.
logService.createLog( options.purpose, options.message, options.credentials, options.error );
}
}
这就是我从控制器传递 logService 实例的方式:
@Controller('auth')
export class AuthController {
constructor( private logService: LogService ) {}
@Post( '/test' )
test(): Promise<any> {
const options = {
purpose: LOG_PURPOSE.TEST,
message: EXCEPTION_MESSAGE.TEST_MESSAGE
};
throw new LoggedConflictException( this.logService, options ); // <- I don't like to pass this.logService every time when I want to log and throw an exception!
// instead I want to have a code that looks like this:
throw new LoggedConflictException( options );
}
}
我希望我的问题是有道理的,并且有人可以帮助任何像我一样努力拥有干净代码的人。
解决方案
推荐阅读
- python - Django 传递用户 ID 来过滤模型
- java - 在 org.slf4j.Logger 中显示以下详细信息的最佳方式是什么?
- flutter - 如何从流生成器返回 null
- batch-file - 如何在来自 LOCALGROUP 的 win cmd bat 上迭代特定组
- statistics - 如何在我的数据框中添加残差值?
- android - Android ACTION_DEVICE_IDLE_MODE_CHANGED 未触发
- typescript - 如何根据字符串值使接口属性有条件
- java - Android:尝试获取 push() 键 ID 并从子元素中提取评分值
- python - tkinter python中的动画光标
- azure-devops - Azure 构建管道 publishUrl 无限期嵌套