CatsService
是一个服务提供者,因为它使用了 @Injectable()
装饰器标记,并且包含了业务逻辑(例如 findAll()
和 addCat()
方法)以及数据状态(例如 cats
数组)。
import { Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {
private readonly cats: string[] = ['Kitty', 'Garfield', 'Tom'];
findAll(): string[] {
return this.cats;
}
addCat(name: string): void {
this.cats.push(name);
}
}
这个服务提供者 CatsService
负责处理与猫咪相关的业务逻辑,比如查找所有猫咪、添加新的猫咪等。在 Nest.js 中,通过 @Injectable()
装饰器标记的类通常被视为服务提供者,用于封装和管理应用程序中的核心功能和业务逻辑。其他组件(比如控制器、中间件等)可以通过依赖注入的方式使用这些服务提供者。