我对 AdonisJS 类有一些问题。
我的代码LoginController
export default class LoginController {
constructor(protected authService: AuthService) {}
@inject()
doLogin({ request }) {
return this.authService.doLogin(request)
}
}
代码验证服务
export default class AuthService {
constructor(private userRepository: UserRepositoryInterface) {}
// login user
@inject()
async doLogin(request: any) {
const { email, password } = request.only(['email', 'password'])
try {
// get user by email
const user = await this.userRepository.getByEmail(email)
if (!user) {
} else {
if (user.active === StatusEnum.ACTIVE) {
const userLogin = this.userRepository.verifyCredentials(email, password)
if (await userLogin) {
const token = this.userRepository.createToken(user)
const response = {
token: token,
}
} else {
}
} else {
}
}
} catch (error) {
}
}
}
我在 LoginController 中调用 AuthService,这样就可以了
private authService = new AuthService
目标是在构造函数中调用以在所有函数代码中使用,错误如下
在执行中我收到此错误
"message": "Cannot construct \"[class LoginController]\" class. Container is not able to resolve its dependencies. Did you mean to use @inject decorator",
"name": "RuntimeException",
"status": 500,
你能帮忙吗?
谢谢你
由于
@inject()
装饰器的位置而出现此错误。
您必须在要注入的位置上使用
@inject()
装饰器。
例如,您必须在类声明上方编写装饰器,以在类的构造函数中注入某些内容。
@inject()
class MyService {
constructor(private someOtherService: SomeOtherService) {}
}
此代码将在构造函数中注入
SomeOtherService
的实例。
如果你想直接向方法中注入一些东西,你必须将装饰器写在方法声明的上方。
class AuthController {
@inject()
doLogin({}: HttpContext, someOtherService: SomeOtherService) {}
}
在这里,我们直接在方法内部注入
SomeOtherService
的实例。
--
因此,要纠正您的问题,您必须在类声明上方编写
@inject()
装饰器,因为您想将依赖项注入类的构造函数中。