How to Inject Angular Services in External JavaScript Functions, and Component’s Static Functions

Balram Chavan
2 min readJun 30, 2022

As your enterprise application starts growing, you come to the point where you have one or many external JavaScript functions from 3rd party libraries, some static functions/classes. The situation becomes interesting when you have to pass data to these functions from the @Injectable() services. In this story, we will try to solve them.

Consuming Angular Service in External JavaScript function

Let’s take a processData() function outside your Angular component. This function does some task by consuming Angular service. Since this function is not part of Angular, how will you pass the instance created by Angular Dependency Injection (DI), to this function?

We need to consume the UserService in processData() function. In HTML file, we will create a division with id to show the users from processData() function.

In dashboard.component.ts file, we will inject Injector service in Dashboard component’s constructor. We shall call processData() function from ngOnInit() by fetching UserService using this.injector.get() function.

Once we have passed the UserService to processData() function, we can start manipulating the DOM to show users.

Consuming Service from component’s “Static” method

Another scenario where we want to pass service to a component’s static function and show data in HTML.

Let’s take ProductService providing us mock product list.