首页 > 解决方案 > 有没有办法通过将服务注入/导入到不是组件/服务/存储库的类中来提高代码质量?

问题描述

在此示例中,我将使用 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 );
    }

}

我希望我的问题是有道理的,并且有人可以帮助任何像我一样努力拥有干净代码的人。

标签: angulardependency-injectionnestjscode-cleanup

解决方案


推荐阅读