Lesson 3
Providers in NestJS
Providers in NestJS

Welcome back! In the previous lessons, we've set up your first NestJS application and explored the essentials of controllers. Now, we're going to dive into another critical part of NestJSProviders. This lesson covers how to create and use providers, with a specific focus on services as providers.

Understanding Providers in NestJS

Providers are a fundamental concept in NestJS. They are used to encapsulate and share functionality across different parts of your application. "Many of the core NestJS classes can act as providers." The key idea behind a provider is that it can be injected as a dependency into other classes, allowing these classes to interact with each other while keeping their concerns separated.

In this unit, we'll focus on services as providers and explore how they can be injected into controllers. Dependency injection, which allows providers to be injected into other classes, is crucial for building modular and maintainable applications. We’ll cover this concept in more depth in the fifth unit of this course, but for now, let’s see how it works in practice.

Creating a Service Provider

Let’s understand services and dependency injection in action through the example of corgis we've previously seen.

TypeScript
1import { Injectable } from '@nestjs/common'; 2 3@Injectable() 4export class CorgiService { 5 getMessage(): string { 6 return 'Exploring the world with Corgis!'; 7 } 8}

The @Injectable() decorator marks this class as a provider. This allows the CorgiService to be injected into other parts of the application. The service contains a method getMessage that returns a string message.

Using the Service in a Controller

Now that we’ve created the CorgiService, let’s see how to use it within a controller by injecting it.

TypeScript
1import { Controller, Get, Render } from '@nestjs/common'; 2import { CorgiService } from './corgi.service'; 3 4@Controller('corgi') 5export class CorgiController { 6 constructor(private readonly corgiService: CorgiService) {} 7 8 @Get() 9 @Render('index') 10 showCorgis() { 11 const message = this.corgiService.getMessage(); 12 return { message }; 13 } 14}

In this code:

  • The CorgiService is injected into the CorgiController through the class constructor.
  • Notice the use of the private syntax in the constructor. This shorthand allows us to declare and initialize the corgiService member in a single step.
  • The showCorgis method then calls the getMessage method from CorgiService and returns its result to the view.
Registering the Provider in the Module

To use the CorgiService, we need to register it in our module.

Similar to controllers, providers must also be registered in the AppModule to make them available for dependency injection throughout the application. We'll cover modules in more detail in the next unit, but for now, just know that registering your provider is essential for NestJS to manage its dependencies properly.

The View Template

Finally, here’s the index.hbs template that has remained unchanged, it will render the message returned by our service:

HTML, XML
1<!DOCTYPE html> 2<html> 3<head> 4 <title>Welcome</title> 5</head> 6<body> 7 <h1>{{message}}</h1> 8</body> 9</html>

This template uses Handlebars syntax to dynamically display the message passed from the controller. The {{message}} placeholder will be replaced by the value returned from the showCorgis method in CorgiController.

In this setup, the controller retrieves the message from the CorgiService using the getMessage method. The service encapsulates the logic for generating this message, keeping the controller's responsibilities focused on handling HTTP requests and responses. The message is then passed to the view, where it is rendered for the user.

Why Providers Matter

Mastering providers is a key step towards building robust NestJS applications. Providers encapsulate business logic, promote code reuse, and keep your controllers clean and focused on handling requests and responses. With this understanding, you’re now ready to move on to the practical part of this lesson and solidify your understanding through hands-on coding.

Let’s dive into some practice and see these concepts in action!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.