Providers are a fundamental concept in Nest. Many of the basic Nest classes may be treated as a provider – services, repositories, factories, helpers, and so on. The main idea of a provider is that it can inject dependencies; this means objects can create various relationships with each other, and the function of “wiring up” instances of objects can largely be delegated to the Nest runtime system. A provider is simply a class annotated with an @Injectable() decorator.
Services
通过命令行创建 Services
1
nest g service cats
执行后结果类似如下
1 2 3 4
$ nest g service cats CREATE src/cats/cats.service.spec.ts (446 bytes) CREATE src/cats/cats.service.ts (88 bytes) UPDATE src/app.module.ts (544 bytes)
创建完src/cats/cats.service.ts代码如下
1 2 3 4
import { Injectable } from'@nestjs/common';
@Injectable() exportclassCatsService {}
修改下,修改前提我们添加一个interface
如果创建interface,命令行命令如下
1 2
$ nest g interface cat CREATE src/cat.interface.ts (24 bytes)
@Post() asynccreate(@Body() createCatDto: CreateCatDto) { this.catsService.create(createCatDto); console.log(createCatDto); return'This action will create a new cat'; }