-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathapp.component.ts
More file actions
95 lines (90 loc) · 2.53 KB
/
app.component.ts
File metadata and controls
95 lines (90 loc) · 2.53 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { CommonModule } from '@angular/common';
import { Component, DestroyRef, inject, OnInit, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { BehaviorSubject, finalize, retry, tap } from 'rxjs';
import { Todo } from './todo';
import { TodoService } from './todo.service';
@Component({
standalone: true,
imports: [CommonModule, MatProgressSpinnerModule],
selector: 'app-root',
template: `
@defer (when !loading()) {
@for (todo of todos(); track todo.id) {
<div>
{{ todo.title }} |
<button (click)="update(todo)">Update</button>
|
<button (click)="delete(todo.id)">Delete</button>
</div>
}
} @loading (minimum 1000) {
<mat-progress-spinner
mode="indeterminate"
value="50"></mat-progress-spinner>
} @error {
<p>There was a problem to load component.</p>
}
`,
styles: [
`
.mdc-circular-progress {
position: absolute;
transition: opacity 250ms 0ms cubic-bezier(0.4, 0, 0.6, 1);
margin: auto;
right: 0;
left: 0;
bottom: 0;
top: 0;
}
`,
],
})
export class AppComponent implements OnInit {
private todoService = inject(TodoService);
private readonly todosSubject$ = new BehaviorSubject<Todo[]>([]);
readonly todos = signal<Todo[]>([]);
loading = signal(true);
private subject$ = inject(DestroyRef);
endLoader(): void {
this.loading.set(false);
}
ngOnInit(): void {
this.todoService
.getAllTodos()
.pipe(
takeUntilDestroyed(this.subject$),
retry(2),
finalize(() => this.endLoader()),
tap((todos) => this.todos.set(todos)),
)
.subscribe();
}
update(todo: Todo) {
this.todoService
.updateSingleTodo(todo)
.pipe(
takeUntilDestroyed(this.subject$),
tap((updatedTodo) => {
this.todos.update((current) =>
current.map((t) => (t.id === updatedTodo.id ? updatedTodo : t)),
);
}),
)
.subscribe();
}
delete(id: number) {
this.todoService
.removeSingleTodo(id)
.pipe(
takeUntilDestroyed(this.subject$),
tap(() => {
const current = this.todosSubject$.value;
this.todosSubject$.next(current.filter((t) => t.id !== id));
this.todos.update((current) => current.filter((t) => t.id !== id));
}),
)
.subscribe();
}
}