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. Here, we'll use a couple of techniques, including the providedIn: 'root'
statement and making sure we only provide the service once in the entire app by using the @Optional()
and @SkipSelf()
decorators.
Getting ready
The project for this recipe resides in the chapter03/start_here/ng-singleton-service
path. 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 similar to the following screenshot: