2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
✈️Getting started with NestJS
✈️Introduction to NestJs Controllers
In the world of NestJS, understanding "Providers" is the key to building robust and maintainable backend services. NestJS, as a modern framework for Node.js, adopts some core concepts of Angular, such as Dependency Injection (DI), and applies them to server-side development. This article will take a deep dive into the Providers mechanism in NestJS, analyze how it works, and how to use them to optimize your application.
In NestJS, Provider is any object that can be managed and injected by the DI container. It can be a class, a value, a factory function, or an abstract interface. The main purpose of Providers is to provide services, values, or factories that can be shared and reused by other modules or components.
In the previous article, we learned about Nest's Controller. This article introduces another important knowledge point: providers. Provider can be understood as the part of the Controller that provides services, which can also be called service.
nest g service news
This is a simple service that currently has two functions: one is to return a list of all news items, and the other is to create a piece of data.
Dependency Injection
Step 1: Introduce the corresponding service and the corresponding interface type in the controller
news.controller.ts
import { NewsService } from './news.service';
import { News } from './interfaces/news.interface';
Step 2: Inject through constructor(private newsService: NewsService) {}
@Controller('news')
export class NewsController {
constructor(private newsService: NewsService) {}
.....
}
Step 3: Use it in the corresponding request decorator
@Controller('news')
export class NewsController {
constructor(private newsService: NewsService) {}
@Get('/page')
async getNewsPageList(@Query() query: string): Promise<News[]> {
console.log(query);
return this.newsService.getNewsPageList();
}
@Post('/create')
async createNews(@Body() createNewsDto: CreateNewsDto) {
console.log(createNewsDto,'添加参数');
return this.newsService.createNews(createNewsDto);
}
}
Step 4: Register in app.module
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { NewsController } from './news/news.controller';
import { NewsService } from './news/news.service';
@Module({
imports: [],
controllers: [AppController, NewsController],
providers: [AppService,NewsService],
})
export class AppModule {}
Mastering Providers in NestJS means you can better build modular and scalable backend services. By using Providers properly, you can easily manage dependencies and improve the readability and maintainability of your code. Whether you are building a complex microservice architecture or a simple API service, NestJS's DI mechanism will be an indispensable tool for you.