初次使用nestjs,在controller中引入俩个service发生报错报错
Error: Nest can't resolve dependencies of the UserController (UserService, ?). Please make sure that the argument RoleService at index [1] is available in the UserModule context.
Potential solutions:
- If RoleService is a provider, is it part of the current UserModule?
- If RoleService is exported from a separate @Module, is that module imported within UserModule?
@Module({
imports: [ /* the Module containing RoleService */ ]
})
at Injector.lookupComponentInParentModules (E:\tiamo\configurableProgram\nest-demo\node_modules\@nestjs\core\injector\injector.js:191:19)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async Injector.resolveComponentInstance (E:\tiamo\configurableProgram\nest-demo\node_modules\@nestjs\core\injector\injector.js:147:33)
at async resolveParam (E:\tiamo\configurableProgram\nest-demo\node_modules\@nestjs\core\injector\injector.js:101:38)
at async Promise.all (index 1)
at async Injector.resolveConstructorParams (E:\tiamo\configurableProgram\nest-demo\node_modules\@nestjs\core\injector\injector.js:116:27)
at async Injector.loadInstance (E:\tiamo\configurableProgram\nest-demo\node_modules\@nestjs\core\injector\injector.js:80:9)
at async Injector.loadController (E:\tiamo\configurableProgram\nest-demo\node_modules\@nestjs\core\injector\injector.js:28:9)
at async Promise.all (index 0)
at async InstanceLoader.createInstancesOfControllers (E:\tiamo\configurableProgram\nest-demo\node_modules\@nestjs\core\injector\instance-loader.js:51:9)
解决办法
1.在user.controller中需要引入其他的role.service,
/*user.controller.js*/
import { Controller, Inject, Get, Post, Param, Req } from '@nestjs/common';
import { UserService } from './user.service';
import { RoleService } from '../role/role.service'
import { User } from './user.entity';
import { Role } from 'src/role/role.entity';
@Controller('user')
export class UserController {
constructor(@Inject('UserService') private userService: UserService, private readonly roleService: RoleService) {
}
@Get('queryUser')
async queryUser(@Req() request): Promise<any> {
// debugger
const promise = this.userService.queryUser(request);
const result = await promise;
return { code: 20000, total: result.length, data: result };
}
}
2.在module中需要引入role的module和service
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { RoleModule } from '../role/role.module'
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { User } from './user.entity';
import { RoleService } from 'src/role/role.service';
@Module({
imports: [TypeOrmModule.forFeature([User]), RoleModule],
providers: [UserService, RoleService],
controllers: [UserController],
exports: [TypeOrmModule]
})
export class UserModule { }