0
0
NestJSframework~15 mins

Injectable decorator in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Injectable Decorator in NestJS
📖 Scenario: You are building a simple NestJS service to manage a list of books in a library. You want to make this service available for other parts of your application by marking it as injectable.
🎯 Goal: Create a NestJS service class called BooksService and use the @Injectable() decorator to make it injectable in other parts of the app.
📋 What You'll Learn
Create a class named BooksService
Use the @Injectable() decorator from @nestjs/common
Define a property books as an array of strings with these exact values: '1984', 'Brave New World', 'Fahrenheit 451'
Add a method getBooks() that returns the books array
💡 Why This Matters
🌍 Real World
Services in NestJS are used to hold business logic and data. Marking them with @Injectable() allows NestJS to manage their lifecycle and inject them where needed.
💼 Career
Understanding how to create injectable services is essential for building scalable and maintainable backend applications with NestJS, a popular Node.js framework.
Progress0 / 4 steps
1
Create the BooksService class with a books array
Create a class called BooksService with a property books that is an array containing the strings '1984', 'Brave New World', and 'Fahrenheit 451'.
NestJS
Need a hint?

Start by writing export class BooksService {} and inside it add books = ['1984', 'Brave New World', 'Fahrenheit 451'];

2
Import the Injectable decorator
Add an import statement to import Injectable from @nestjs/common at the top of the file.
NestJS
Need a hint?

Write import { Injectable } from '@nestjs/common'; at the top of your file.

3
Add the @Injectable() decorator to BooksService
Add the @Injectable() decorator exactly above the BooksService class declaration.
NestJS
Need a hint?

Place @Injectable() right before export class BooksService.

4
Add a getBooks() method to return the books array
Inside the BooksService class, add a method called getBooks() that returns the books array.
NestJS
Need a hint?

Write a method getBooks() that returns this.books.