BackEnd/Node.js
[Node.js] 모듈 exports하고 imports해서 다른모듈 사용하기
Cune
2022. 7. 1. 15:55
A모듈 내에 있는 A서비스에 있는 메서드를 B모듈 내 컨트롤러에서 사용하고 싶은 경우!
AModule.ts
-AService를 내보내기
@Module({
controllers: [AController],
providers: [AService],
exports: [AService],
})
export class AModule { }
AService.ts
@Injectable()
export class AService {
getHi(){
return "Hi";
}
BModule.ts
-AModule을 가져오기 (A모듈안에 A서비스가 있기 때문)
@Module({
imports: [AModule],
controllers: [BController],
providers: [BService],
})
export class BModule { }
BController.ts
-A서비스 인스턴스를 만들어서 사용
@Controller()
export class BController {
constructor(private readonly aService: AService) { }
@Get('/hi')
getHi(): string {
return this.aService.getHi();
}
}
*전역모듈로 사용하는 경우에는 @Global() 데코레이터를 모듈에 선언하면 된다!