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
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { CatService } from '../services/cat.service';
import { ToastComponent } from '../shared/toast/toast.component';
import { Cat } from '../shared/models/cat.model';
@Component({
selector: 'app-cats',
templateUrl: './cats.component.html',
styleUrls: ['./cats.component.scss']
})
export class CatsComponent implements OnInit {
cat = new Cat();
cats: Cat[] = [];
isLoading = true;
isEditing = false;
addCatForm: FormGroup;
name = new FormControl('', Validators.required);
age = new FormControl('', Validators.required);
weight = new FormControl('', Validators.required);
constructor(private catService: CatService,
private formBuilder: FormBuilder,
public toast: ToastComponent) { }
ngOnInit() {
this.getCats();
this.addCatForm = this.formBuilder.group({
name: this.name,
age: this.age,
weight: this.weight
});
}
getCats() {
this.catService.getCats().subscribe(
data => this.cats = data,
error => console.log(error),
() => this.isLoading = false
);
}
addCat() {
this.catService.addCat(this.addCatForm.value).subscribe(
res => {
this.cats.push(res);
this.addCatForm.reset();
this.toast.setMessage('item added successfully.', 'success');
},
error => console.log(error)
);
}
enableEditing(cat: Cat) {
this.isEditing = true;
this.cat = cat;
}
cancelEditing() {
this.isEditing = false;
this.cat = new Cat();
this.toast.setMessage('item editing cancelled.', 'warning');
// reload the cats to reset the editing
this.getCats();
}
editCat(cat: Cat) {
this.catService.editCat(cat).subscribe(
() => {
this.isEditing = false;
this.cat = cat;
this.toast.setMessage('item edited successfully.', 'success');
},
error => console.log(error)
);
}
deleteCat(cat: Cat) {
if (window.confirm('Are you sure you want to permanently delete this item?')) {
this.catService.deleteCat(cat).subscribe(
() => {
const pos = this.cats.map(elem => elem._id).indexOf(cat._id);
this.cats.splice(pos, 1);
this.toast.setMessage('item deleted successfully.', 'success');
},
error => console.log(error)
);
}
}
}