Creating a singleton service using providedIn
In this recipe, you’ll learn several tips on how to ensure your Angular service is being used as a singleton. This means that there will only be one instance of your service in the entire application. We’ll use a couple of techniques, including the providedIn: 'root'
statement, making sure we only provide the service once in the entire app by using the @Optional()
and @SkipSelf()
decorators.
Getting ready
The app that we are going to work with resides in start/apps/chapter03/ng-singleton-service
inside the cloned repository:
- Open the code repository in your code editor.
- Open the terminal, navigate to the code repository directory, and run the following command to serve the project:
npm run serve ng-singleton-service
This should open the app in a new browser tab, and you should see the following:
Figure 3.7: The ng-singleton-service app running on http://localhost...