SERVICES AND DEPENDENCY INJECTION IN ANGULAR
Service & Dependency Injection In Angular (PART-1)

Pre-requisites

  • Classes and objects.
  • Constructor.
  • Functions / Methods.
  • Angular components.

Angular Application

  • As we all know that Angular uses the concept of components.
  • The Entire UI of the Angular application is divided into several components.
Red blocks highlighting components
  • Sometimes all these components performing common tasks like displaying images on the view, accessing the database etc
  • To avoid writing code again and again, Angular Services comes into place.
  • These services can then be injected into the components that require that service or dependency.
Service & Dependency Injection In Angular
Service & Dependency Injection In Angular

Services In Angular

  • Service is nothing its just a class with specific purpose.
    • Data Sharing Across multiple components.
    • It is used to apply application logic
    • We can use Services for external interactions such as connecting to a database.
  • The main objective of a service is to organize and share business logic, models, or data and functions with different components of an Angular application.
  • Services are piece of code that are used to perform a specific task, a service can contain a value or function or combination of both.
  • Services prevent us from writing the same code at multiple sections of our application.
  • The best solution is to write services and inject in application where we need it.
  • Services are usually implemented through dependency injection.

Naming Convention For Service

FileName.service.ts

Example
Student.service.ts

Scenario Without Dependency Injection

Scenario Without Dependency Injection
Scenario Without Dependency Injection

Dependency Injection as a Design Pattern

Dependency Injection is a coding pattern in which a class receives its dependencies from external sources rather than creating them itself.

With DI VS Without DI In Angular
Dependency Injection as a Design Pattern
Dependency Injection In Angular

Dependency Injection In Angular

  1. Register with injector.
  2. Create StudentService service class.
  3. Add the StudentService service / dependency in StudentsData and StudentsList components.
Dependency Injection In Angular

2 ways to register service in Angular

  1. App Level
    If you want the service in your all components then register service at App level.
  2. Component Level
    If you want the service in your particular component then register service with Component level.

Source Code

student-service.service.ts – Service Class Code

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

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

  constructor() { }
  getStudents() {
    return [
      { name: "Adil", age: 21, standard: 12 },
      { name: "Kumar", age: 19, standard: 11 },
      { name: "Zain", age: 18, standard: 10 }
    ];
  }
}

app.module.ts File Code – Where we register service

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { UserComponent } from './user/user.component';
import { InlineComponent } from './inline/inline.component';
import { Inline1Component } from './inline1/inline1.component';
import { Inline2Component } from './inline2/inline2.component';
import { Inline3Component } from './inline3/inline3.component';
import { InterpolationComponent } from './interpolation/interpolation.component';
import { EventsComponent } from './events/events.component';
import { BindingsComponent } from './bindings/bindings.component';
import { ClassBindingComponent } from './class-binding/class-binding.component';
import { NgClassDirComponent } from './ng-class-dir/ng-class-dir.component';
import { StyleBindingComponent } from './style-binding/style-binding.component';
import { TemplateReferenceComponent } from './template-reference/template-reference.component';
import { StructureDirectivesComponent } from './structure-directives/structure-directives.component';
import { TwoWayComponent } from './two-way/two-way.component';
import { ChildComponent } from './child/child.component';
import { Child2Component } from './child2/child2.component';
import { PipesComponent } from './pipes/pipes.component';
import { CustomPipe } from './pipes/custom.pipe';
import { StudentsListComponent } from './students-list/students-list.component';
import { StudentsDataComponent } from './students-data/students-data.component';
import { StudentServiceService } from './services/student-service.service';

@NgModule({
  declarations: [
    AppComponent,
    UserComponent,
    InlineComponent,
    Inline1Component,
    Inline2Component,
    Inline3Component,
    InterpolationComponent,
    EventsComponent,
    BindingsComponent,
    ClassBindingComponent,
    NgClassDirComponent,
    StyleBindingComponent,
    TemplateReferenceComponent,
    StructureDirectivesComponent,
    TwoWayComponent,
    ChildComponent,
    Child2Component,
    PipesComponent,
    CustomPipe,
    StudentsListComponent,
    StudentsDataComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [StudentServiceService],
  bootstrap: [AppComponent]
})
export class AppModule { }

students-data.component.ts – Component File Code – TS File

import { Component, OnInit } from '@angular/core';
import { StudentServiceService } from '../services/student-service.service';

@Component({
  selector: 'app-students-data',
  templateUrl: './students-data.component.html',
  styleUrls: ['./students-data.component.css'],
  // providers: [StudentServiceService]
})
export class StudentsDataComponent implements OnInit {
  public students:any;
  // public students = [
  //   {name:"Adil",age:21,standard:12},
  //   {name:"Kumar",age:19,standard:11},
  //   {name:"Zain",age:18,standard:10}
  // ];
  constructor(private std:StudentServiceService) {
    this.students = std.getStudents();
    console.log(std.getStudents());
  }

  ngOnInit(): void {
  }

}

students-data.component.html – Component File Code – HTML File

<h1>students-data works!</h1>
<table height="200" width="200">
    <tr>
        <th>NAME</th>
        <th>AGE</th>
        <th>CLASS</th>
    </tr>
    <tr *ngFor="let std of students">
        <td>{{ std.name }}</td>
        <td>{{ std.age }}</td>
        <td>{{ std.standard }}</td>
    </tr>
</table>

students-list.component.ts – Component File Code – TS File

import { Component, OnInit } from '@angular/core';
import { StudentServiceService } from '../services/student-service.service';

@Component({
  selector: 'app-students-list',
  templateUrl: './students-list.component.html',
  styleUrls: ['./students-list.component.css'],
  // providers:[StudentServiceService]
})
export class StudentsListComponent implements OnInit {
  public students:any;
  // public students = [
  //   {name:"Adil",age:21,standard:12},
  //   {name:"Kumar",age:19,standard:11},
  //   {name:"Zain",age:18,standard:10}
  // ];
  constructor(private std:StudentServiceService) {
    this.students = std.getStudents();
    console.log(std.getStudents());
  }

  ngOnInit(): void {
  }

}

students-list.component.html – Component File Code – HTML File

<h1>students-list works!</h1>
<table height="200" width="200">
    <tr>
        <th>NAME</th>
        <!-- <th>AGE</th>
        <th>CLASS</th> -->
    </tr>
    <tr *ngFor="let std of students">
        <td>{{ std.name }}</td>
        <!-- <td>{{ std.age }}</td>
        <td>{{ std.standard }}</td> -->
    </tr>
</table>

app.component.html File Code

<p>Welcome To Angular By Learning Never Ends</p>
<app-students-list></app-students-list>
<br/>
<app-students-data></app-students-data>

Download Notes Of This Blog, From The Link Given Below.

https://www.mediafire.com/file/ukvwf6fvpm4ms79/30+-+DEPENDENCY+INJECTION.pptx/file

Download Source Code Of This Blog, From The Link Given Below.

https://www.mediafire.com/file/gks4brn26htufze/Service+And+DI.rar/file

No responses yet

Leave a Reply

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