- Dependency Injection (DI) is a application design pattern.
- Angular has its own DI framework and used to increase the efficiency and the modularity of Angular applications.
- DI framework provides declared dependencies to a class when that class is instantiated
Let us see the implementation of DI in Angular application.
In this example, we will create CourseListComponent to display the List of Courses information. Initially we will display the information without using the services/dependency Injection. Later we will use the dependency Injection and display the courses information. CourseListComponent gets courses from the COURSES array, an in-memory collection defined in a separate mock-courses file.
Step 1: Create the Angular Application as shown below
C:\Users\Girish>ng new my-diapp
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS
CREATE my-diapp/angular.json (3609 bytes)
CREATE my-diapp/package.json (1282 bytes)
CREATE my-diapp/README.md (1024 bytes)
...........
Step 2: Create course.ts
as shown below
export class Course {
id: number;
name: string;
code: string;
duration: number;
fee: number;
}
Step 3: Create mock-courses.ts
as shown below
import { Course } from './course';
export const COURSES: Course[] = [
{ id: 11, name: 'Python', code:'PY',duration: 30, fee: 300},
{ id: 12, name: 'Angular', code:'NG',duration: 30, fee: 200 },
{ id: 13, name: 'Java', code:'JSE',duration: 30, fee: 400},
{ id: 14, name: 'C#', code:'CS',duration: 30, fee: 400},
{ id: 15, name: 'Scala', code:'SC',duration: 30, fee: 300 },
{ id: 16, name: 'TypeScript', code:'TS',duration: 30, fee: 200 },
{ id: 17, name: 'Dart', code:'DART',duration: 30, fee: 100 },
{ id: 18, name: 'Go', code:'GO',duration: 30, fee: 100 },
{ id: 19, name: 'JavaScript', code:'JS',duration: 30, fee: 100},
{ id: 20, name: 'Swift', code:'SWIFT',duration: 30, fee: 200}
];
Step 4: General Course List Component as shown below
C:\Users\Girish\my-diapp>ng g component course-list
CREATE src/app/course-list/course-list.component.html (26 bytes)
CREATE src/app/course-list/course-list.component.spec.ts (657 bytes)
CREATE src/app/course-list/course-list.component.ts (288 bytes)
CREATE src/app/course-list/course-list.component.css (0 bytes)
UPDATE src/app/app.module.ts (493 bytes)
Step 5: Update course-list.component.ts
as shown below
import { Component, OnInit } from '@angular/core';
import { COURSES } from '../mock-courses';
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.css']
})
export class CourseListComponent implements OnInit {
courses = COURSES;
constructor() { }
ngOnInit() {
}
}
Step 6: Update course-list.component.css
as shown below
table {
border-collapse: collapse;
border: 1px solid black;
}
th,td {
border: 1px solid black;
}
table.a {
table-layout: auto;
width: 300px;
}
Step 7: Update course-list.component.html
as shown below
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Code</th>
<th>Duration</th>
<th>Fee</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let course of courses">
<td>{{course.id}}</td>
<td>{{course.name}}</td>
<td>{{course.code}}</td>
<td>{{course.duration}}</td>
<td>{{course.fee}}</td>
</tr>
</tbody>
</table>
Step 8: Update app.component.ts
as shown below
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h2>Courses</h2>
<app-course-list></app-course-list> `,
//templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my-diapp';
}
Step 9: Now run the application as shown below
C:\Users\Girish\my-diapp>ng serve
Step 10: Now Let us implement the Dependency Injection by Creating the Injectable Service class as shown below
C:\Users\Girish\my-diapp>ng generate service course
CREATE src/app/course.service.spec.ts (333 bytes)
CREATE src/app/course.service.ts (135 bytes)
Step 11: Now Import the Service class and add to the providers list inside the app.module.ts
file as shown below. The @NgModule() and @Component() decorators have the providers metadata option, where you can configure providers for NgModule-level or component-level injectors.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CourseListComponent } from './course-list/course-list.component';
import { CourseService } from './course.service';
@NgModule({
declarations: [
AppComponent,
CourseListComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [CourseService],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 12: Now update the course.service.ts
as shown below
import { Injectable } from '@angular/core';
import { COURSES } from './mock-courses';
@Injectable({
providedIn: 'root'
})
export class CourseService {
getCourses() {
return COURSES;
}
}
Step 13: Now update the course-list.component.ts
as shown below. Here we are injecting the CourseService to the CourseListComponent constructor.
import { Component, OnInit } from '@angular/core';
import { Course } from '../course';
import { CourseService } from '../course.service';
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.css']
})
export class CourseListComponent implements OnInit {
courses: Course[];
constructor(courseService: CourseService) {
this.courses = courseService.getCourses();
}
ngOnInit() {
}
}
Now if you run the application, you can see the same screen as earlier. But this time you have used the Service class dependency injection to get the data of courses.
References
- https://angular.io/guide/dependency-injection
Learn more about Angular features in the upcoming blog articles.
Happy Learning!