Dependency Injection in Angular

 Dependency Injection in Angular


Dependency injection is used in Angular to provide instances of objects to other objects that need them. Here is an example of dependency injection in Angular:


import { Injectable } from '@angular/core';


@Injectable({

  providedIn: 'root',

})

export class Logger {

  log(message: string) {

    console.log(message);

  }

}


@Injectable({

  providedIn: 'root',

})

export class UserService {

  constructor(private logger: Logger) {}


  getUsers() {

    this.logger.log('Fetching users...');

    // code to get users from API

  }

}

This code sets up a Logger service and a UserService that depends on the Logger. When the getUsers function is called, it logs a message to the console using the injected Logger.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...