Configuring an injector with a DI token
In this recipe, you'll learn how to create a basic DI token for a regular TypeScript class to be used as an Angular service. We have a service (UserService
) in our application, which currently uses the Greeter
class to create a user with a greet
method. Since Angular is all about DI and services, we'll implement a way in which to use this regular TypeScript class, named Greeter
, as an Angular service. We'll use InjectionToken
to create a DI token and then the @Inject
decorator to enable us to use the class in our service.
Getting ready
The project that we are going to work with resides in chapter03/start_here/ng-di-token
, which is inside the cloned repository. Perform the following steps:
- Open the project in Visual Studio Code.
- Open the Terminal and run
npm install
to install the dependencies of the project. - Once done, run
ng serve -o
.This should open the app in a new browser tab; you should see something...