新手入门NestJS(十三)- Providers - Services
Providers是什么,看下官网的解释
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 | $ nest g service cats |
创建完src/cats/cats.service.ts
代码如下
1 | import { Injectable } from '@nestjs/common'; |
修改下,修改前提我们添加一个interface
如果创建interface
,命令行命令如下
1 | $ nest g interface cat |
创建完src/cat.interface.ts
代码如下
1 | export interface Cat {} |
修改后src/cats/cats.service.ts
的代码如下
1 | import { Injectable } from '@nestjs/common'; |
顺便修改src/cat.interface.ts,代码如下
1 | export interface Cat { |
下面看下如何在Controller中应用
1 | constructor(private catsService: CatsService) {} |
上面代码是主要关注的地方
另外需要导入对应的包
1 | import { Cat } from 'src/cat.interface'; |
然后访问http://127.0.0.1:3000/cats
会得到一个空数组
执行下面的命令
1 | $ curl -d 'name=durban1&age=12&bread=1' http://127.0.0.1:3000/cats |
然后在访问http://127.0.0.1:3000/cats
类似如下的数据
1 | [{"name":"durban1","age":"12","bread":"1"},{"name":"durban1","age":"12","bread":"1"}] |