Add add and delete functionality for ducks
Signed-off-by: Gergely Polonkai <gergely@polonkai.eu>
This commit is contained in:
parent
7c36ce1282
commit
267b229e13
@ -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()
|
||||
|
@ -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>
|
||||
|
@ -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;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user