Dependency Injection And Zones In Angular

In this article, we will learn about dependency injection and zones in angular.

Dependency Injection :

When you develop a smaller part of your system, like a module or a class, you will need certain external dependencies.

Dependencies are services or objects that a class needs to perform its function.

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

@Injectable({
  providedIn: 'root'
})
export class DemoServiceService {

  constructor() { }

  getCurrentDate(){
    return new Date();
  }
}

In this service, I have created a common function, which returns the current date.

we can use this service in any other service or another component with the help of the dependency injection.

dependency injection makes it easy to use the service at multiple places in multiple components and reduces code redundancy.

import { Component } from '@angular/core';
import { DemoServiceService } from '../shared/service/demo-service.service';

@Component({
  selector: 'app-forms',
  templateUrl: './forms.component.html',
  styleUrls: ['./forms.component.scss']
})
export class FormsComponent {

  constructor(private demoService: DemoServiceService) {}

  getDate(){
    this.demoService.getCurrentDate();
  }
}

In the above figure, I have imported “DemoServiceService” in “FormsComponent “.

now with the object of “DemoServiceService”, we can access any function or object of this service in “FormsComponent “.

This can be done because of dependency injection.

Zones :

A zone is an associate execution context that persists across async tasks. you’ll be able to consider it as thread-local storage for JavaScript VMs. This guide describes the way to use Angular’s NgZone to mechanically discover changes within the part to update hypertext markup language.

While Zone.js will monitor all the states of synchronous and asynchronous operations, Angular in addition provides a service known as zone.

export class AppComponent implements OnInit {
  constructor(private ngZone: NgZone) {}
  ngOnInit() {
    this.ngZone.runOutsideAngular(() => {
      setTimeout(() => {
        console.log('Outside Done!');
      });
    });
  }
}

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories