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 NestJS—Providers. This lesson covers how to create and use providers, with a specific focus on services as providers.
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.
Let’s understand services and dependency injection in action through the example of corgis we've previously seen.
TypeScript1import { 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.
Now that we’ve created the CorgiService
, let’s see how to use it within a controller by injecting it.
TypeScript1import { 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 theCorgiController
through the class constructor. - Notice the use of the
private
syntax in the constructor. This shorthand allows us to declare and initialize thecorgiService
member in a single step. - The
showCorgis
method then calls thegetMessage
method fromCorgiService
and returns its result to the view.
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.
Finally, here’s the index.hbs
template that has remained unchanged, it will render the message returned by our service:
HTML, XML1<!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.
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!