AshKeys

Confessions and Confusions of a Freelance Fullstacker.

Ashok Mannolu Arunachalam, How toAngularDI
Back

How to add third party library as Angular Dependency

There are scenarios where you want to access a global namespace (e.g window) or a third party library in your Angular application.

Of course, it is still possible to access it using window.thirdPartyInstance. However, it is not always the case.

Lazy or async initialization

Consider a scenario, where we only get this instance after the third party script has loaded by the browser and some startup stuff happened. Nowadays, this is a de facto start up steps because libraries want to be performant and do not want to block user interaction or the consumer process.

ts
Library.onReady(() => {
console.log(
`library is loaded now.
You can access it referring window.thirdPartyInstance`
);
});

All you have to know here is that you are ready to use it when the callback is invoked.

Injection Token to the rescue

Using injection tokens, we can create the third party instance as dependency and inject it whenever and whereever we want.

Create the injection token

ts
const ThirdPartyLibrary = new InjectionToken<InstanceType>(
'LibraryInstance', {
// yes, you can provide it in which context you prefer.
provideIn: 'root',
// This is only called when it is injected.
factory: () => window.thirdPartyInstance
});

Inject as a dependency

ts
import { Injectable, Inject } from '@angular/core';
@Injectable()
class ThirdPartyService {
constructor(
@Inject(ThirdPartyLibrary) public library: InstanceType
) { }
useLibrary() {
return this.library.doSomething();
}
}