Creating a singleton service using forRoot()
In this recipe, you’ll learn how to use ModuleWithProviders and the forRoot() statement to ensure your Angular service is used as a singleton in the entire app. We’ll start with an app that has multiple instances of NotificationsService, and we’ll implement the necessary code to make sure we end up with a single instance of the service in our application.
Getting ready
The app that we are going to work with resides in start/apps/chapter03/ng-singleton-service-forroot, 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-forrootThis should open the app in a new browser tab, and you should see the following:

Figure 3.10: The ng-singleton-service-forroot app running on http://localhost:4200