Nest 中在当前模块使用其他模块 service 的方式

 

https://blog.csdn.net/zgd826237710/article/details/101445481

当前模块使用其他模块 service 方式
将其他模块的 module 导入到 当前模块 module 文件中的 imports 中

在当前模块需要的地方,比如 controller 或 service 文件中引入其他模块的 service,并在对应文件的 constructor 函数参数中使用 private readonly otherService: otherService 的方式注入

在其他路由方法中即可使用 this.otherService 的方式调用其他模块 service 中定义的方法

示例
Chat 模块
chat-service.ts

```js
import { Injectable } from '@nestjs/common';

@Injectable()
export class ChatService {
getHello(): string {
return 'Hello World!';
}
}
```

chat-controller.ts
```js
import { Controller, Get } from '@nestjs/common';
import { ChatService } from './chat.service';

@Controller()
export class ChatController {
constructor(private readonly chatService: ChatService) {}

/**
* Hello World
*/
@Get()
getHello(): string {
return this.chatService.getHello();
}
}
```
chat-module.ts

```js
import { Module } from '@nestjs/common';
import { ChatController } from './chat.controller';
import { ChatService } from './chat.service';

@Module({
imports: [],
controllers: [ChatController],
providers: [ChatService],
// 将 ChatService 暴露出去
exports: [ChatService],
})
export class ChatModule {}
```
User 模块(在 User 模块中使用 ChatService)
user-service.ts

```js
import { Injectable } from '@nestjs/common';

@Injectable()
export class UserService {
}
```

user-controller.ts
```js
import { Controller, Get } from '@nestjs/common';
import { ChatService } from '../chat/chat.service';
import { UserService } from './user.service';

@Controller()
export class ChatController {

// 注入 chatService
constructor(private readonly userService: UserService, private readonly chatService: ChatService) {}

/**
* 调用 chatService 方法
*/
@Get('chat/hello')
getChatHello(): string {
return this.chatService.getHello();
}
}
```
user-module.ts
```js
import { Module } from '@nestjs/common';
import { ChatModule } from '../chat/chat.module';
import { UserController } from './user.controller';
import { UserService } from './user.service';

@Module({
imports: [ChatModule],
controllers: [UserController],
providers: [UserService],
exports: [],
})
export class UserModule {}
```
所有模块都要记得放到 AppModule 的 imports 数组中,否则无法生效。
————————————————
版权声明:本文为CSDN博主「浮沉半生」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zgd826237710/article/details/101445481

posted @ 2021-10-22 15:58  小猪冒泡  阅读(1678)  评论(0编辑  收藏  举报