Move duck list to a service

Signed-off-by: Gergely Polonkai <gergely@polonkai.eu>
This commit is contained in:
Gergely Polonkai 2016-09-06 14:43:07 +02:00
parent 06af47fccf
commit 8c0ecca40f
4 changed files with 69 additions and 10 deletions

View File

@ -1,21 +1,27 @@
import { Component } from "@angular/core"; import { Component, OnInit } from "@angular/core";
import { Duck } from "./models"; import { Duck } from "./models";
import { DuckService } from "./duck.service";
const DUCKS: Ducks[] = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'pink' }
]
@Component({ @Component({
selector: "duckbook-front", selector: "duckbook-front",
templateUrl: "/app/app.component.html" templateUrl: "/app/app.component.html",
providers: [ DuckService ]
}) })
export class AppComponent { export class AppComponent implements OnInit {
ducks = DUCKS; ducks = [];
selectedDuck: Duck; selectedDuck: Duck;
constructor(private duckService: DuckService) {}
ngOnInit(): void {
this.getDucks();
}
getDucks(): void {
this.duckService.getDucks().then(ducks => this.ducks = ducks);
}
onSelect(duck: Duck): void { onSelect(duck: Duck): void {
console.log(duck); console.log(duck);
this.selectedDuck = duck; this.selectedDuck = duck;

11
app/duck.service.ts Normal file
View File

@ -0,0 +1,11 @@
import { Injectable } from "@angular/core";
import { Duck } from "./models";
import { DUCKS } from "./mocked-data";
@Injectable()
export class DuckService {
getDucks(): Promise<Duck[]> {
return Promise.resolve(DUCKS);
}
}

35
app/ducks.component.ts Normal file
View File

@ -0,0 +1,35 @@
import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { Duck } from "./models";
import { DuckService } from "./duck.service";
@Component({
selector: "ducks",
templateUrl: "/app/ducks.component.html",
providers: [ DuckService ]
})
export class DucksComponent implements OnInit {
ducks = [];
selectedDuck: Duck;
constructor(private router: Router,
private duckService: DuckService)
{}
ngOnInit(): void {
this.getDucks();
}
getDucks(): void {
this.duckService.getDucks().then(ducks => this.ducks = ducks);
}
onSelect(duck: Duck): void {
this.selectedDuck = duck;
}
gotoDetail(duck: Duck): void {
this.router.navigate(['/detail', duck.id]);
}
}

7
app/mocked-data.ts Normal file
View File

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