Skip to content

Commit

Permalink
Angular service using HTTP client
Browse files Browse the repository at this point in the history
  • Loading branch information
amejiarosario committed Jun 7, 2020
1 parent 15f6e25 commit a93291c
Showing 1 changed file with 20 additions and 34 deletions.
54 changes: 20 additions & 34 deletions src/app/todo/todo.service.ts
@@ -1,59 +1,45 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

const API = '/api/todos';
export interface ITodo {
_id?: string;
title: string;
isDone: boolean;
notes: string;
update_at: string;
editing ?: boolean;
}

let TODOS = [
{ title: 'Install Angular CLI', isDone: true },
{ title: 'Style app', isDone: true },
{ title: 'Finish service functionality', isDone: false },
{ title: 'Setup API', isDone: false },
];
const API = '/api/todos';

@Injectable({
providedIn: 'root'
})
export class TodoService {

constructor(private http: HttpClient) { }

get(params = {}) {
return this.http.get(API, { params });
}

add(data) {
return new Promise(resolve => {
TODOS.push(data);
resolve(data);
});
add(data: ITodo) {
return this.http.post(API, data);
}

put(changed) {
return new Promise(resolve => {
const index = TODOS.findIndex(todo => todo === changed);
TODOS[index].title = changed.title;
resolve(changed);
});
put(changed: ITodo) {
return this.http.put(`${API}/${changed._id}`, changed);
}

delete(selected) {
return new Promise(resolve => {
const index = TODOS.findIndex(todo => todo === selected);
TODOS.splice(index, 1);
resolve(true);
});
toggle(selected: ITodo) {
selected.isDone = !selected.isDone;
return this.put(selected);
}

deleteCompleted() {
return new Promise(resolve => {
TODOS = TODOS.filter(todo => !todo.isDone);
resolve(TODOS);
});
delete(selected: ITodo) {
return this.http.delete(`${API}/${selected._id}`);
}

toggle(selected) {
selected.isDone = !selected.isDone;
return Promise.resolve();
deleteCompleted(body = { isDone: true }) {
return this.http.request('delete', `${API}`, { body });
}

}

0 comments on commit a93291c

Please sign in to comment.