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 being 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 app.
Getting ready
The project for this recipe resides in the chapter03/start_here/ng-singleton-service-forroot
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. The app should appear as follows:
Now that we have the app running, in the next section, we can move on to the...