Welcome back to CodeYourCraft! Today, we're diving deep into the world of Angular by exploring the @Injectable decorator. This powerful tool helps us manage dependencies in our applications and keeps our code clean and modular. Let's get started!
Before we dive into the @Injectable decorator, let's first understand what Dependency Injection (DI) is all about.
Dependency Injection is a software design pattern that allows us to manage dependencies between classes in a loosely coupled way. In other words, it helps us separate the different parts of our application, making them easier to manage, test, and reuse.
@Injectable Decorator 💡In Angular, we use the @Injectable() decorator to mark a class as a service that can be injected into other classes. This allows us to easily manage dependencies between classes without having to hard-code them.
Here's a simple example:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LoggerService {
log(message: string) {
console.log(message);
}
}In this example, we've created a LoggerService that logs messages to the console. We've marked it as an injectable service using the @Injectable decorator.
@Injectable Service ✅Now that we have our LoggerService set up, let's use it in another class:
import { Injectable, Inject } from '@angular/core';
import { LoggerService } from './logger.service';
@Injectable()
export class GreetingService {
constructor(private logger: LoggerService) { }
greet(name: string) {
this.logger.log(`Hello, ${name}!`);
}
}In this example, we've created a GreetingService that greets someone using the LoggerService. We've injected the LoggerService into the GreetingService constructor using Angular's dependency injection system.
Let's take this a step further and create a more complex example. We'll create a UserService that fetches user data from a backend API and a GreetingComponent that greets the user.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class UserService {
private apiUrl = 'https://api.example.com/users';
constructor(private http: HttpClient) { }
getUser(id: number) {
return this.http.get(`${this.apiUrl}/${id}`);
}
}
import { Injectable, Inject } from '@angular/core';
import { UserService } from './user.service';
@Injectable()
export class GreetingComponent {
user: any;
constructor(private userService: UserService) {
this.userService.getUser(1).subscribe(user => {
this.user = user;
});
}
greet() {
console.log(`Hello, ${this.user.name}!`);
}
}In this example, we've created a UserService that fetches user data from a backend API. We've also created a GreetingComponent that greets the user. The GreetingComponent uses the UserService to fetch the user data and greets the user when the greet() method is called.
That's it for today! We've covered what Dependency Injection is, how to use the @Injectable decorator to mark services as injectable, and how to use these services in other classes.
What is Dependency Injection?
Stay tuned for more lessons on Angular! Until next time, happy coding! 🚀🚀