Angular — Wrapping Third-party libraries

Jawadhasan
3 min readJun 9, 2023
Photo by Ryunosuke Kikuno on Unsplash

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.

--

--

Jawadhasan

Software Solutions Team Lead | Cloud Architect | Solutions Architect