#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

src/app/app.module.ts
import { TodoListService } from './todo-list.service';

Next, add the service to the providers array, so that the NgModule looks like this:

src/app/app.module.ts:
@NgModule({
  declarations: [
    AppComponent,
    InputComponent,
    ItemComponent,
    ListManagerComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [TodoListService],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

src/app/todo-list.service.ts
  private todoList = [
    { title: 'install NodeJS' },
    { title: 'install Angular CLI' },
    { title: 'create new app' },
    { title: 'serve app' },
    { title: 'develop app' },
    { title: 'deploy app' },
  ];

Create a method to return the list

Now add a getTodoList method that will return the todoList array. The service will look like this:

src/app/todo-list.service.ts
import { Injectable } from '@angular/core';

@Injectable()
export class TodoListService {

  private todoList = [
    { title: 'install NodeJS' },
    { title: 'install Angular CLI' },
    { title: 'create new app' },
    { title: 'serve app' },
    { title: 'develop app' },
    { title: 'deploy app' },
  ];

  constructor() { }

  getTodoList() {
    return this.todoList;
  }
}

Inject and use the service

src/app/list-manager/list-manager.component.ts
import { TodoListService } from '../todo-list.service';

Now remove the todoList array, but keep the todoList member:

src/app/list-manager/list-manager.component.ts
  todoList;

Change the constructor to be:

src/app/list-manager/list-manager.component.ts
constructor(private todoListService:TodoListService) { }

And now use the service to assign the todoList array inside the ngOnInit method:

src/app/list-manager/list-manager.component.ts
ngOnInit() {
  this.todoList = this.todoListService.getTodoList();
}

Last updated