Angular – Wrapping Third-party libraries

Introduction

It is very common in web applications that we’ll want to use third-party libraries or components.

Let’s see how we can take something like that and turn it into an injectable service in Angular.

If you are new to angular, you can check previous posts for the background information.

toastr

For demo, we’ll use toastr, which is a JavaScript library for non-blocking notifications.

Step-1

First, install toastr using npm

npm install toastr

This will give us toastr StyleSheet and JavaScript file. Lets import those into angular next.

Step-2

Update angular.json file with toastr style-sheet and JavaScript file as follows:

Ok, now toaster will be loaded (globally) with our app, but the question is, how do we make this consumable as an angular service and use it in our components?

First, lets try to use toastr in our component next.

Step-3

Use toastr in component, as shown below

First I’ve created a button on device-card.component

next the detailClicked method as follows (notice the typescript error indicator)

even though toastr is available globally, Typescript doesn’t know about it. We can solve it by declare the toastr variable as shown below

declaring toaster this way, just let Typescript know, that toastr variable is in scope, already declared somewhere else.

Lets test it by clicking the details button the card and we’ll see the success notifications as shown below:

even though it is working, there are issues with this approach

  • Using a global reference is not a good idea.
  • It is not testable (coz not injectable).

To address these issues, we can wrap toastr into an angular service. Let’s do this next.

Step 4

Following code shows a simple service to wrap toaster.

toastr is still in global scope, but now at least accessing global scope is limited to this class and we won’t be using it all over our application. Also, we have now an injectable service to use.

Step 5

This service can be now injected into the component as just like any other service and used:

we can now test by clicking the button again that it is working as expected.

You can download the source code from this git repository.

The deployed application can be checked on this URL.

Summary

In this post, we learned how to wrap a third-party library inside an Angular service to use it in our application. We saw that wrapping a library which exposes a global object into an angular service, help us control its exposure to some degree, promotes testability and enhance developer experience.

Let me know if you have some questions or comments. Till next time, happy coding.