Angular dependency injection04:33

  • 0
Published on October 10, 2017

Text version of the video

Slides

Angular 2 Tutorial playlist

Angular 2 Text articles and slides

All Dot Net and SQL Server Tutorials in English

All Dot Net and SQL Server Tutorials in Arabic

In this video we will discuss
1. What is Dependency Injection
2. How dependency injection works in angular

Let us understand Dependency Injection in Angular with an example. Consider this piece of code in EmployeeListComponent.
export class EmployeeListComponent implements OnInit {

private _employeeService: EmployeeService;

constructor(_employeeService: EmployeeService) {
this._employeeService = _employeeService;
}

ngOnInit() {
this._employeeService.getEmployees()
.subscribe(
employeesData =] this.employees = employeesData,
error =] this.statusMessage = ‘Error’);
}

// Rest of the code
}

1. We register a service with the angular injector by using the providers property of @Component decorator or @NgModule decorator.

2. When a component in Angular needs a service instance, it does not explicitly create it. Instead it just specifies it has a dependency on a service and needs an instance of it by including the service as a constructor parameter.

3. When an instance of the component is created, the angular injector creates an instance of the service class and provides it to component constructor.

4. So the component which is dependent on a service instance, receives the instance from an external source rather than creating it itself. This is called Dependency Injection.

What is Dependency Injection
It’s a coding pattern in which a class receives its dependencies from an external source rather than creating them itself.

So if we relate this definition to our example, EmployeeListComponent has a dependency on EmployeeService. The EmployeeListComponent receives the dependency instance (i.e EmployeeService instance) from the the external source (i.e the angular injector) rather than creating the instance itself.

1. Why should we use Dependency Injection?
2. What benefits it provide?
3. Why can’t we explicitly create an instance of the EmployeeService class using the new keyword and use that instance instead in our EmployeeListComponent?

We will answer these questions in our next video.

https://cafeadobro.ro/

https://www.stagebox.uk/wp-includes/depo10-bonus10/

depo 25 bonus 25

https://parfumschristianblanc.com/

Enjoyed this video?
"No Thanks. Please Close This Box!"