模块

Module is a class with @Module({}) decorator. This decorator provides metadata, which framework uses to organize application structure.

模块是一个带有@Module({})装饰器的类。该装饰器为框架提供组织应用程序结构的元数据。

图片标题

Right now, it is our ApplicationModule:

现在,我们来准备ApplicationModule

import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
    controllers: [ UsersController ],
    components: [ UsersService ],
})
export class ApplicationModule {}

By default, modules encapsulate each dependency. It means, that it is not possible to use its components / controllers outside module. Each module can also import another modules. In fact, you should think about Nest Modules as a tree of modules. Let's move UsersController and UsersService to UsersModule. Simply create new file e.g. users.module.ts with below content:

默认情况下,模块封装每一个依赖。也就是说,只能在模块内部使用模块的组件/控制器。 在每一个模块中都可以导入其他模块。实际上,你可以将Nest模块看作是一颗模块树。 将 UsersControllerUsersService 移动至UsersModule,只需要简单创建一个文件,例如users.module.ts。以下是文件内容:

import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
    controllers: [ UsersController ],
    components: [ UsersService ],
})

export class UsersModule {} Then import UsersModule into ApplicationModule (our main application module):

import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';

@Module({
    modules: [ UsersModule ]
})
export class ApplicationModule {}

It's everything. As might be seen, with Nest you can naturally split your code into separated and reusable modules!

接下来,你就可以使用Nest将你的代码拆分成一个个可重复使用的模块了。

分享实例

You already know that Module encapsulates its components. What if you want to share instance between two or more modules? With Nest - it is pretty easy. You only have to use@Shared() decorator and add exports array, just like that:

我们都知道每个模块封装它们的组件。那么要想在模块之间分享组件该怎么办呢?有了Nest,你只需要使用@Shared()装饰器并且添加输出数组,就可以轻松分享组件了。以下是一个示例:

import { Module, Shared } from '@nestjs/common';

@Shared()
@Module({
    controllers: [ UsersController ],
    components: [ UsersService ],
    exports: [ UsersService ],
})
export class UsersModule {}

That's all. It is especially powerful feature. You can read more about it in Advanced / SharedModule section.

这是一个很强大的功能。更多关于分享组件的信息请阅读Advanced / SharedModule章节。

依赖注入

Module can easily inject components, which belongs to itself:

每个模块可以轻松注入它自己的组件:

@Module({
    controllers: [ UsersController ],
    components: [ UsersService, ChatGateway ],
})
export class UsersModule implements NestModule {
    constructor(private usersService: UsersService) {}
}

Furthermore, components also can inject modules:

此外,组件也可以注入模块:

export class UsersController {
    constructor(private module: UsersModule) {}
}

results matching ""

    No results matching ""