Dependency Injection in Angular.

chitaranjan biswal
2 min readDec 15, 2022

Dependency injection is an software design pattern in which one class or object requires another object. In angular dependency injection is, components using services without creating that service within that class rather than requiring that service from another class ,hence angular will inject that service in the components whenever required.

Suppose we have a component called MyComponent that depends on a service called MyService. To use dependency injection, we would first define MyService as a provider in our Angular module

@Injectable({
providedIn: 'root'
})
export class MyService {
// Service code goes here
}

In this example, the MyService class is marked as a provider using the @Injectable decorator, and is registered with the root injector using the providedIn property. This means that MyService will be available to inject into any component or service in the application, without having to register it explicitly with each module or component that needs it.

Next, we would declare that MyComponent depends on MyService by adding it to the component's constructor.

@Component({
// Component metadata goes here
})
export class MyComponent {
constructor(private myService: MyService) {
// Inject an instance of MyService into the component
}
}

Lets added some services and inject them in MyComponent

@Injectable({
providedIn: 'root'
})
export class MyService {
private user: User;

constructor(private http: HttpClient) {}

getUser(): Observable<User> {
return this.http.get<User>('/api/user');
}

updateUser(user: User): Observable<User> {
return this.http.put<User>('/api/user', user);
}
}

Now ,we have added getUser ,updateUser service to the MyService

Let’s use that in our components

// Component

@Component({
// Component metadata goes here
})
export class MyComponent {
constructor(private userService: UserService) {}

ngOnInit() {
// Use the injected instance of UserService
this.userService.getUser().subscribe(user => {
this.user = user;
});
}

save() {
this.userService.updateUser(this.user).subscribe();
}
}

Thanks for reading.

--

--