services
folder inside the app
folder. Then use the Angular Generator to create the service named todo-list
.src/app/services/todo-list.service.ts
. The service is a simple Class called TodoListService
. It has the decorator @Injectable
which allows it to use Dependency Injection.NgModule
. But you can keep on reading to understand what happens and what it means.NgModule
. We have only one NgModule
in our app - the AppModule
located in /src/app/app.module.ts
. It's an empty class preceded by the @NgModule
decorator to which we pass a configuration object. One of the properties of this object is a providers
list which is currently empty. We'll add our new service to the list.providers
array tells Angular how to provide a service we're looking for (usually in a component or another service). This time the recipe is simple: When we ask for the TodoListService
class we expect to get an instance of this class. Angular will create only one instance that we can access from anywhere in our application (a Singleton), so we can use it to share data between different parts of the application.todoList
array from ListManagerComponent
to our new service. Go to the generated service file, src/app/services/todo-list.service.ts
, and add this code inside the TodoListService
class just above the constructor
:getTodoList
method that will return the todoList
array. The service will look like this:list-manager
component. In Angular Dependency Injection is very simple. We pass it as a parameter in the constructor - the parameter's type is the class name of the service. Angular assigns the instance it created to the parameter name, and we can use it from within the constructor. Before implementing it ourselves, let's see how it works:private
or public
before the parameter name it is automatically assigned to this
. So instead of declaring and assigning the property by ourselves:list-manager
component.todoList
property declaration.TodoListService
using the constructor. TodoListService
is imported.ngOnInit
method.