We can transfer any data through our apps, transform and replace it at any level.
So we can make the architecture simpler and more flexible with clear data flow and low coupling. It also makes testing and replacing our dependencies easy.
Nevertheless, I think that DI in Angular applications is used rather modestly. It is usually an injection of service or providing some global data top-down through the app.
In this article, I want to show an alternative way to work with data from DI. The purpose is to simplify components, directives, and services that use it.
I review Angular code every day during my work and opensource projects. The uses of DI in most apps is limited by the following cases:
ChangeDetectorRef
, ElementRef
and other from DI.API_URL
in the app.module
and get this URL in any entity in the app when you need it.Sometimes developers transform already existing global token in a more convenient format. A good sample of such a transformation is a WINDOW
token from a package @ng-web-apis/common.
Angular has a DOCUMENT
token to get a page object in any place of your app. That way your components do not depend on global objects. It is easy to test them and nothing gets broken by Server-Side Rendering.
If you want to get a _window_
object more often, you can make the following token:
import {DOCUMENT} from '@angular/common';
import {inject, InjectionToken} from '@angular/core';
export const WINDOW = new InjectionToken<Window>(
'An abstraction over global window object',
{
factory: () => {
const {defaultView} = inject(DOCUMENT);
if (!defaultView) {
throw new Error('Window is not available');
}
return defaultView;
},
},
);
<>
When someone requests WINDOW
token the first time from DI, Angular executes a token factory. It takes a DOCUMENT
object and gets a link to a window object from it.
If you feel uncertain in your DI skills, try the first free chapter in angular.institute. There is much information about how DI works and how to use it effectively
Now I want to propose another way to make such transformations to move them into providers field of component or directive that injects the result.
#angular #dependency-injection #typescript #angular di