Skip to main content

Angular Service & Dependency Injection

·153 words·1 min
Programing Web development Angular Frontend Development
Anurag Konduru
Author
Anurag Konduru
Software Engineer (Front-End Developer/Linuxuser/Software Explorer)
Learning Angular - This article is part of a series.

Angular Service & Dependency Injection
#

Services:
#

Services in Angular serve as repositories for reusable code, facilitating storage and accessibility throughout the application.

  • Example: filename.service.ts
    import { Injectable } from '@angular/core';
    
    @Injectable({
    providedIn: 'root'
    })
    export class LoggingService {
      logStatusChange(status: string) {
        console.log("Status: ", status);
      }
    }
    
  • The optimal approach to using a service is through dependency injection.

Angular Dependency Injection:
#

In Angular, Dependency Injection is about components and services getting what they need from a central source, making things modular and easy to manage.

Usage in Component:
#

import { LoggingService } from 'path/to/logging.service';

export class YourComponent {
  constructor(private log: LoggingService) {}

  ngOnInit() {
    this.log.logStatusChange('Some Text Status');
  }
}

Service Injection IMG

Example: Making it Injectable in a Component:
#

@Component({
  // Other component configurations
  providers: [LoggingService],
})
  • Add your service into the providers array of @Component or your module, and just like that,you can used it wherever needed inside the module scope.
Learning Angular - This article is part of a series.

Related

Angular Directives: Guiding the DOM with Instructions
·687 words·4 mins
Programing Web development Angular Frontend Development
Directives: # Directives are instructional elements within the DOM.
Angular Databinding: Connecting TypeScript and HTML
·285 words·2 mins
Programing Web development Angular Frontend Development
Data Binding # When it comes to data binding in Angular, the synergy between TypeScript and HTML is facilitated through various techniques:
Angular Component: Building Blocks for Reusability and Modularity
·474 words·3 mins
Programing Web development Angular Frontend Development
Components: # Components in Angular play a pivotal role in enhancing reusability and Modularity in web pages.