-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathtodo.service.ts
More file actions
51 lines (46 loc) · 1.46 KB
/
Copy pathtodo.service.ts
File metadata and controls
51 lines (46 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { randText } from '@ngneat/falso';
import { Observable, catchError, throwError } from 'rxjs';
import { Todo } from './todo';
@Injectable({
providedIn: 'root',
})
export class TodoService {
constructor(private http: HttpClient) {}
getAllTodos(): Observable<Todo[]> {
return this.http
.get<Todo[]>('https://jsonplaceholder.typicode.com/todos')
.pipe(catchError((err) => this.throwErrorMessage(err)));
}
updateSingleTodo(todo: Todo): Observable<Todo> {
return this.http
.put<Todo>(
`https://jsonplaceholder.typicode.com/todos/${todo.id}`,
{
id: todo.id,
title: randText(),
userId: todo.userId,
completed: todo.completed,
},
{
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
},
)
.pipe(catchError((err) => this.throwErrorMessage(err)));
}
removeSingleTodo(id: number): Observable<null> {
return this.http
.delete<null>(`https://jsonplaceholder.typicode.com/todos/${id}`, {
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.pipe(catchError((err) => this.throwErrorMessage(err)));
}
throwErrorMessage(err: HttpErrorResponse): Observable<never> {
return throwError(() => new Error(err?.message || 'Server error'));
}
}