Using Angular DI tokens
In this recipe, you’ll learn how to create a basic DI token. We will create it for a regular TypeScript class, to be used as an Angular service using DI. We have a class named Jokes in our application, which is used in the AppComponent by manually creating a new instance of the class. This makes our code tightly coupled and hard to test, since the AppComponent class directly uses the Jokes class.
In other words, when running the tests for the App component, we now rely on the Jokes class, and if something changes in that class, our test will break. Since Angular is all about DI and services, we’ll use a DI token to use the Jokes class as an Angular service. We’ll use the InjectionToken method to create a DI token, and then the @Inject decorator to enable us to use the class in our service.
Getting ready
The app that we are going to work with resides in start/apps/chapter03/ng-di-token inside the cloned repository:
-
...