Add add and delete functionality for ducks

Signed-off-by: Gergely Polonkai <gergely@polonkai.eu>
This commit is contained in:
Gergely Polonkai 2016-09-06 16:49:18 +02:00
parent 7c36ce1282
commit 267b229e13
3 changed files with 45 additions and 0 deletions

View File

@ -18,6 +18,13 @@ export class DuckService {
return Promise.reject(error.message || error);
}
create(color: string): Promise<Duck> {
return this.http.post(this.ducksUrl, JSON.stringify({color: color}), {headers: this.headers})
.toPromise()
.then((res) => res.json().data)
.catch(this.handleError);
}
update(duck: Duck): Promise<Duck> {
const url = `${this.ducksUrl}/${duck.id}`;
@ -27,6 +34,15 @@ export class DuckService {
.catch(this.handleError);
}
delete(id: number): Promise<void> {
let url = `${this.ducksUrl}/${id}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
getDucks(): Promise<Duck[]> {
return this.http.get(this.ducksUrl)
.toPromise()

View File

@ -3,8 +3,14 @@
<ul>
<li *ngFor="let duck of ducks" (click)="onSelect(duck)">
{{ duck.color }}
<button (click)="delete(duck); $event.stopPropagation()">Delete</button>
</li>
</ul>
<div>
<label>Duck color:</label>
<input #duckColor>
<button (click)="add(duckColor.value); duckColor.value = ''">Add</button>
</div>
<div *ngIf="selectedDuck">
{{ selectedDuck.color }}
<button (click)="gotoDetail(selectedDuck)">Edit</button>

View File

@ -32,4 +32,27 @@ export class DucksComponent implements OnInit {
gotoDetail(duck: Duck): void {
this.router.navigate(['/detail', duck.id]);
}
add(color: string): void {
// Make sure the color is not empty
color = color.trim();
if (!color) { return; }
this.duckService.create(color)
.then(duck => {
this.ducks.push(duck);
this.selectedDuck = null;
});
}
delete(duck: Duck): void {
this.duckService.delete(duck.id)
.then(() => {
this.ducks = this.ducks.filter(d => d !== duck);
if (this.selectedDuck === duck) {
this.selectedDuck = null;
}
});
}
}