This article will describe a common scenario of using some libraries which don’t have Angular integration. As an example, I will use HashWords library which converts hash strings to the human-readable random words. If you are lazy to read an article, you can check Github repo for the code examples.
Installing library by running: $ npm install --save hashwords
Importing it to the .angular-cli.json:
_“scripts”_: [“../node_modules/hashwords/dist/hashwords.min.js”]
By the last action, we made it available on the window object.
Now, we can register it in the providers property of theNgModule
providers: [{ provide: 'Hashwords', useValue: window['hashwords']() }]
Provide the application with the Value
_window['hashwords']()_
for any injection called Hashwords!
Next action is to inject this newly created value to the constructor of the app.component.ts
With the @Inject({ token: any })
decorator we can manually Inject registered dependencies. When @[Inject](https://angular.io/api/core/Inject)()
is not present, [Injector](https://angular.io/api/core/Injector)
will use the type annotation of the parameter. That’s what actually happens in the application where we use constructor(apiService: ApiService)
.
The previous example is totally workable. But we are missing the brilliant feature of Angular + TypeScript applications — type check! Of course, not every library you need has type definition out of the box. But with the InjectionToken mechanism, we can define some basic interface for our third-party library and provide our application with the knowledge of properties and methods which we are going to use.
LOC 3: Import needed dependencies from libs.providers.ts
;
LOC 12: Now we can Inject Hashword
InjectionToken, and define a type for hashwords variable, which is going to be interface — IHashwords
;
LOC 15,16: After that action we can use hashwords
methods with the intellisense!
With the flexible mechanism of registering providers in Angular applications, we can easily wrap 3rd party libraries and use them across application exactly as if they where an Angular library.
With the Injection Token mechanism, we can even define custom types and make our app aware of API of an imported library!
If you want to get an info straight from the horse’s mouth follow me on Twitter and Medium account!