diff --git a/app/duck.service.ts b/app/duck.service.ts index 68c4fe8..4d25b08 100644 --- a/app/duck.service.ts +++ b/app/duck.service.ts @@ -18,6 +18,13 @@ export class DuckService { return Promise.reject(error.message || error); } + create(color: string): Promise { + 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 { const url = `${this.ducksUrl}/${duck.id}`; @@ -27,6 +34,15 @@ export class DuckService { .catch(this.handleError); } + delete(id: number): Promise { + let url = `${this.ducksUrl}/${id}`; + + return this.http.delete(url, {headers: this.headers}) + .toPromise() + .then(() => null) + .catch(this.handleError); + } + getDucks(): Promise { return this.http.get(this.ducksUrl) .toPromise() diff --git a/app/ducks.component.html b/app/ducks.component.html index e33bdc7..6ccf63f 100644 --- a/app/ducks.component.html +++ b/app/ducks.component.html @@ -3,8 +3,14 @@
  • {{ duck.color }} +
+
+ + + +
{{ selectedDuck.color }} diff --git a/app/ducks.component.ts b/app/ducks.component.ts index 0c10b2a..fe19d18 100644 --- a/app/ducks.component.ts +++ b/app/ducks.component.ts @@ -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; + } + }); + } }