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 headers = new Headers({"Content-Type": "application/json"});
|
2016-10-27 15:52:55 +00:00
|
|
|
private ducksUrl = 'app/ducks';
|
2016-09-06 13:54:03 +00:00
|
|
|
|
|
|
|
constructor(private http: Http) {}
|
|
|
|
|
2016-10-27 15:52:55 +00:00
|
|
|
getDucks(): Promise<Duck[]> {
|
|
|
|
return this.http.get(this.ducksUrl)
|
|
|
|
.toPromise()
|
|
|
|
.then(response => response.json().data as Duck[])
|
|
|
|
.catch(this.handleError);
|
2016-09-06 14:49:18 +00:00
|
|
|
}
|
|
|
|
|
2016-10-27 15:52:55 +00:00
|
|
|
getDuck(id: number): Promise<Duck> {
|
|
|
|
return this.getDucks()
|
|
|
|
.then(ducks => ducks.find(duck => duck.id === id));
|
2016-09-06 13:54:03 +00:00
|
|
|
}
|
|
|
|
|
2016-10-27 15:52:55 +00:00
|
|
|
create(name: string): Promise<Duck> {
|
|
|
|
return this.http.post(this.ducksUrl, JSON.stringify({name: name}), {headers: this.headers})
|
|
|
|
.toPromise()
|
|
|
|
.then(res => res.json().data)
|
|
|
|
.catch(this.handleError);
|
2016-09-06 14:49:18 +00:00
|
|
|
}
|
|
|
|
|
2016-10-27 15:52:55 +00:00
|
|
|
private handleError(error: any): Promise<any> {
|
|
|
|
console.error("An error occured", error);
|
2016-09-06 13:35:20 +00:00
|
|
|
|
2016-10-27 15:52:55 +00:00
|
|
|
return Promise.reject(error.message || error);
|
2016-09-06 13:35:20 +00:00
|
|
|
}
|
2016-09-06 12:43:07 +00:00
|
|
|
}
|