2016-09-06 12:43:07 +00:00
|
|
|
import { Injectable } from "@angular/core";
|
2016-09-06 13:54:03 +00:00
|
|
|
import { Headers, Http } from "@angular/http";
|
|
|
|
|
|
|
|
import "rxjs/add/operator/toPromise";
|
2016-09-06 12:43:07 +00:00
|
|
|
|
|
|
|
import { Duck } from "./models";
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class DuckService {
|
2016-09-06 13:54:03 +00:00
|
|
|
private ducksUrl = 'app/ducks';
|
|
|
|
private headers = new Headers({"Content-Type": "application/json"});
|
|
|
|
|
|
|
|
constructor(private http: Http) {}
|
|
|
|
|
|
|
|
private handleError(error: any): Promise<any> {
|
|
|
|
console.error("An error occured", error);
|
|
|
|
|
|
|
|
return Promise.reject(error.message || error);
|
|
|
|
}
|
|
|
|
|
2016-09-06 14:49:18 +00:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2016-09-06 13:54:03 +00:00
|
|
|
update(duck: Duck): Promise<Duck> {
|
|
|
|
const url = `${this.ducksUrl}/${duck.id}`;
|
|
|
|
|
|
|
|
return this.http.put(url, JSON.stringify(duck), {headers: this.headers})
|
|
|
|
.toPromise()
|
|
|
|
.then(() => duck)
|
|
|
|
.catch(this.handleError);
|
|
|
|
}
|
|
|
|
|
2016-09-06 14:49:18 +00:00
|
|
|
delete(id: number): Promise<void> {
|
|
|
|
let url = `${this.ducksUrl}/${id}`;
|
|
|
|
|
|
|
|
return this.http.delete(url, {headers: this.headers})
|
|
|
|
.toPromise()
|
|
|
|
.then(() => null)
|
|
|
|
.catch(this.handleError);
|
|
|
|
}
|
|
|
|
|
2016-09-06 12:43:07 +00:00
|
|
|
getDucks(): Promise<Duck[]> {
|
2016-09-06 13:54:03 +00:00
|
|
|
return this.http.get(this.ducksUrl)
|
|
|
|
.toPromise()
|
|
|
|
.then(response => response.json().data as Duck[])
|
|
|
|
.catch(this.handleError);
|
2016-09-06 12:43:07 +00:00
|
|
|
}
|
2016-09-06 13:35:20 +00:00
|
|
|
|
|
|
|
getDuck(id: number): Promise<Duck> {
|
|
|
|
return this.getDucks().then(ducks => ducks.find(duck => duck.id === id));
|
|
|
|
}
|
2016-09-06 12:43:07 +00:00
|
|
|
}
|