Skip to content

Many of the basic Nest classes, such as services, repositories, factories, and helpers, can be treated as providers. The key idea behind a provider is that it can be injected as a dependency, allowing objects to form various relationships with each other.

1.快速生成

shell
nest g service [name]

# or

nest g service [name] --no-spec

2.基础语法

ts
// cats.service.ts
import { Injectable } from '@nestjs/common';
import { Cat } from './interfaces/cat.interface';

@Injectable()
export class CatsService {
  private readonly cats: Cat[] = [];

  create(cat: Cat) {
    this.cats.push(cat);
  }

  findAll(): Cat[] {
    return this.cats;
  }
}

然后可以在 cats.controller.ts 中使用 CatsService

ts
// cats.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';

@Controller('cats')
export class CatsController {
  constructor(private catsService: CatsService) {}

  @Post()
  async create(@Body() createCatDto: CreateCatDto) {
    this.catsService.create(createCatDto);
  }

  @Get()
  async findAll(): Promise<Cat[]> {
    return this.catsService.findAll();
  }
}

TIP

constructor(private catsService: CatsService) {}

  1. private catsService: CatsServiceNestJS 通过 构造函数参数 知道需要一个 CatsService 的实例

    NestJS 利用了 TypeScript 的装饰器元数据系统,在编译时,如果启用了 emitDecoratorMetadataTypeScript 会为这个类生成类似的元数据:

    ts
    Reflect.getMetadata('design:paramtypes', CatsController); 
    // 输出: [CatsService]
  2. private 关键字表示同时将这个参数赋值给类的成员变量 this.catsService

这是 TypeScript 的语法糖(和 NestJS 无关),它在 编译阶段自动将构造函数参数变成类的属性,并赋值给 this.xxx

ts
class CatsController {
  constructor(private catsService: CatsService) {}
}
// 等同于:
class CatsController {
  private catsService: CatsService;

  constructor(catsService: CatsService) {
    this.catsService = catsService;
  }
}