Move to the in-memory web API

This also makes it possible to save data.

Signed-off-by: Gergely Polonkai <gergely@polonkai.eu>
This commit is contained in:
Gergely Polonkai 2016-09-06 15:54:03 +02:00
parent 29a0eb7f33
commit 7c36ce1282
6 changed files with 52 additions and 9 deletions

View File

@ -1,6 +1,10 @@
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { HttpModule } from "@angular/http";
import { InMemoryWebApiModule } from "angular2-in-memory-web-api";
import { InMemoryDataService } from "./in-memory-data.service";
import { routing } from "./app.routing";
@ -15,6 +19,8 @@ import { DuckService } from "./duck.service";
imports: [
BrowserModule,
FormsModule,
HttpModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
routing
],
declarations: [

View File

@ -7,5 +7,6 @@
<label>color: </label>
<input [(ngModel)]="duck.color" placeholder="Color" />
</div>
<button (click)="save()">Save</button>
<button (click)="goBack()">Back</button>
</div>

View File

@ -26,6 +26,11 @@ export class DuckDetailComponent implements OnInit {
window.history.back();
}
save(): void {
this.duckService.update(this.duck)
.then(this.goBack);
}
@Input()
duck: Duck;
}

View File

@ -1,12 +1,37 @@
import { Injectable } from "@angular/core";
import { Headers, Http } from "@angular/http";
import "rxjs/add/operator/toPromise";
import { Duck } from "./models";
import { DUCKS } from "./mocked-data";
@Injectable()
export class DuckService {
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);
}
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);
}
getDucks(): Promise<Duck[]> {
return Promise.resolve(DUCKS);
return this.http.get(this.ducksUrl)
.toPromise()
.then(response => response.json().data as Duck[])
.catch(this.handleError);
}
getDuck(id: number): Promise<Duck> {

View File

@ -0,0 +1,13 @@
import { InMemoryDbService } from "angular2-in-memory-web-api";
export class InMemoryDataService implements InMemoryDbService {
createDb() {
let ducks = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'pink' }
];
return {ducks};
}
}

View File

@ -1,7 +0,0 @@
import { Duck } from "./models";
export const DUCKS: Duck[] = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'pink' }
];