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.
First, install toastr using npm
npm install toastr
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.
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.