Advertisement
Guest User

Untitled

a guest
Mar 12th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import {Injectable} from '@angular/core';
  2. import {Todo} from './todo';
  3.  
  4. @Injectable()
  5. export class TodoDataService {
  6.  
  7.   // Placeholder for last id so we can simulate
  8.   // automatic incrementing of id's
  9.   lastId: number = 0;
  10.  
  11.   // Placeholder for todo's
  12.   todos: Todo[] = [];
  13.  
  14.   constructor() {
  15.   }
  16.  
  17.   // Simulate POST /todos
  18.   addTodo(todo: Todo): TodoDataService {
  19.     if (!todo.id) {
  20.       todo.id = ++this.lastId;
  21.     }
  22.     this.todos.push(todo);
  23.     return this;
  24.   }
  25.  
  26.   // Simulate DELETE /todos/:id
  27.   deleteTodoById(id: number): TodoDataService {
  28.     this.todos = this.todos
  29.       .filter(todo => todo.id !== id);
  30.     return this;
  31.   }
  32.  
  33.   // Simulate PUT /todos/:id
  34.   updateTodoById(id: number, values: Object = {}): Todo {
  35.     let todo = this.getTodoById(id);
  36.     if (!todo) {
  37.       return null;
  38.     }
  39.     Object.assign(todo, values);
  40.     return todo;
  41.   }
  42.  
  43.   // Simulate GET /todos
  44.   getAllTodos(): Todo[] {
  45.     return this.todos;
  46.   }
  47.  
  48.   // Simulate GET /todos/:id
  49.   getTodoById(id: number): Todo {
  50.     return this.todos
  51.       .filter(todo => todo.id === id)
  52.       .pop();
  53.   }
  54.  
  55.   // Toggle todo complete
  56.   toggleTodoComplete(todo: Todo) {
  57.     let updatedTodo = this.updateTodoById(todo.id, {
  58.       complete: !todo.complete
  59.     });
  60.     return updatedTodo;
  61.   }
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement