Technology Sharing

Getting Started with NestJs Providers

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Nest Learning Series

✈️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.

🚩什么是 Providers

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.

🚩如何创建一个 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.
insert image description here
insert image description here

🚩service如何为controller提供服务

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';
  • 1
  • 2

Step 2: Inject through constructor(private newsService: NewsService) {}

@Controller('news')
export class NewsController {
	constructor(private  newsService: NewsService) {}
	.....
}
  • 1
  • 2
  • 3
  • 4
  • 5

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);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

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 {}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Conclusion

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.