Controller负责处理Request及产生Response,数据库存取或是业务逻辑(business logic)通常写在Service class里
业务逻辑以最简单hello world为例
export class AppService {
sayHello(): string {
return 'Hello World! in App Service';
}
}
在app.controller.ts里
...
import { AppService } from './app.service';
@Controller()
export class AppController {
// 宣告变量,型別为AppService
appService: AppService;
// 建立AppController实例,一并建立AppService实例
constructor(){
this.appService = new AppService();
}
@Get()
sayHello(){
// 呼叫AppService的sayHello方法,回传client
return this.appService.sayHello();
}
...
}
Postman结果
nest.js提供Dependency Injection(DI, 相依注入),可以不用每次要用AppService的时候都要new,让nest.js DI机制帮我们处理相依class
nest.js的DI几乎是从Angular整套借来用。
在app.module.ts中providers注册AppService
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
到app.controller.ts,把要注入的AppService当作contructor参数
@Controller()
export class AppController {
appService: AppService;
// 将要注入的AppService当作constructor传入参数
constructor(_appService: AppService){
// 把注入的AppService指定给controller变量
this.appService = _appService;
}
@Get()
sayHello(){
return this.appService.sayHello();
}
...
}
Postman测试得到一样的结果
Typescript提供一种complier sugar(语法糖),可以再简化代码
@Controller()
export class AppController {
// appService: AppService;
// 以private 修饰 appService
// 等同于注释掉的代码
constructor(
private appService: AppService
// _appService:AppService
){
//this.appService = _appService;
}
@Get()
sayHello(){
return this.appService.sayHello();
}
...
}
Providers有三種
- Value
- Class
- Factory
下一章继续将Providers
推荐一下我的公众号: 【 geekjc 】,微信号: 【 c8706288 】一起学习交流编程知识,分享经验,各种有趣的事。