Dependency Injection in Angular 1 vs Angular 2
- In Angular 2, the directive and component decorators are the place where you configure dependency injection bindings.
- An instance of the login service will be created next to the App component.
- In Angular 1, it can be done as follows: – – There is often a need for a component to interact with its DOM element.
- It uses the same dependency injection mechanism to inject the element into the component’s constructor.
- Angular 2 provides a single API for injecting services, directives, and elements.
Your migration to AngularJS 2 could be a lot less tricky if you take a look at how these common dependency injection scenarios translate from Angular 1 to 2.
In this article I will show how common scenarios of using dependency injection in Angular 1 can be implemented in Angular 2.
I wrote the code samples in TypeScript because I am a big fan of the language. This does not mean you have to use it when building applications in Angular 2. The framework works great with ES5 and ES6.
Now, the same component implemented in Angular 2.
Experienced developers know that coupling of the login component to the login service is problematic. It is hard to test this component in isolation. And it also makes it less reusable. If we have two applications, with two login services, we will not be able to reuse our login component.
We can remedy it by monkey patching the system loader, so we can replace the login service, but this is not the right solution. We have a fundamental problem with our design, which DI can help us fix.
We can solve our problem by injecting an instance of LoginService into the constructor instead of creating it directly.
Now, we need to tell the framework how to create an instance of the service.
All right, let’s port this example to Angular 2.
As with Angular 1, we need to tell the framework…