我已阅读有关分层注入的 nestjs 文档的文章。但我在实施它时遇到了问题。目前,我有两个模块。
AuthModule
是导入的模块UserModule
。UserModule
包含在其他模块中使用的服务(它可以正常工作)。
auth.module.ts
import * as passport from 'passport';
import {
Module,
NestModule,
MiddlewaresConsumer,
RequestMethod,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import {JwtStrategy} from './jwt.straegy';
import {UserModule} from '../shared/user/user.module';
@Module({
imports: [UserModule],
components: [AuthService, JwtStrategy],
exports: [AuthService]
})
export class AuthModule implements NestModule {
public configure(consumer: MiddlewaresConsumer) {
consumer
.apply(passport.authenticate('jwt', { session: false }))
.forRoutes({ path: '/cats', method: RequestMethod.ALL });
}
}
用户模块.ts
import {Module} from '@nestjs/common';
import {MongooseModule} from '@nestjs/mongoose';
import {UserSchema} from '../../schema/user.schema';
import {UserService} from './user.service';
@Module({
imports: [
MongooseModule.forFeature([{ name: 'UserInterface', schema: UserSchema }])
],
components: [UserService],
exports: [UserService]
})
export class UserModule {}
当nestjs 将UserService 注入AuthService 时,就会出现问题。遇到以下错误。从构造函数中删除服务是可行的。奇怪的是 UserService 在其他模块中工作。
Error: Nest can't resolve dependencies of the AuthService (?). Please verify whether [0] argument is available in the current context.
auth.service.ts
import * as jwt from 'jsonwebtoken';
import { Component } from '@nestjs/common';
import {UserService} from '../shared/user/user.service';
@Component()
export class AuthService {
constructor(private readonly userService: UserService) {}
async createToken(username) {
const expiresIn = 60 * 60, secretOrKey = 'i am fake!';
const user = {username};
const token = jwt.sign(user, secretOrKey, {expiresIn});
return {
expires_in: expiresIn,
access_token: token
};
}
async validateUser(signedUser): Promise<boolean> {
return !!(await this.userService.findByUsername(signedUser.username));
}
}