#15: π Creating a Service
In Angular, a service is (typically) a JavaScript class that's responsible for performing a specific task needed by your application. In our todo-list application, we'll use a service to save all the tasks, and use it by injecting it into the components.
Create the service
In order to create a new service with the Angular CLI, make sure you're in the root folder of your application, then right click and select service as option. Name the service todoList
.
It will generate the service and put it under src/app/todo-list.service.ts
. It has the decorator @Injectable
which allows it to use Dependency Injection.
Make the service a provider
To start using the service, we first need to provide it in an ngModule. Start by adding this code in src/app/app.module.ts:
Next, add the service to the providers
array, so that the NgModule looks like this:
This tells Angular to provide (that is, create and inject) an instance of our service when we ask for it anywhere in our application.
Move the todo list from component to service
We now need to move the todoList
array from ListManagerComponent
to our new service. Go to the generated service file, todo-list.service.ts, and add this code just above the constructor:
Create a method to return the list
Now add a getTodoList
method that will return the todoList
array. The service will look like this:
Inject and use the service
After creating the service, we can inject it into our list-manager component. Go to the folder π src/app/list-manager/ list-manager.component.ts and add the following import code:
Now remove the todoList
array, but keep the todoList
member:
Change the constructor to be:
And now use the service to assign the todoList
array inside the ngOnInit
method:
Last updated