Services
The applications we create handle volumes of data. Most of the data will be retrieved from services and will be reused in various parts of the application. Let's create a service that can retrieve data using http
. The service should be loosely coupled with components, as the primary focus of the component should be to support the view. So, the service can be injected to components using a dependency injection. This approach will enable us to mock the service in order to unit test the component.
Let's create a simple TodoService
that returns a list of Todo
items. The code snippet of TodoService
is shown here. TodoService
has a property named todos
of the type array that can hold a collection of Todo
items and is hardcoded with the Todo
items in the constructor:
import {Injectable} from '@angular/core'; import { Todo } from './todo'; @Injectable() export class TodoService { todos: Array<Todo>; constructor() { this.todos = [ {"title": "First Todo",...