From: Kai Moritz Date: Sat, 2 May 2020 17:45:42 +0000 (+0200) Subject: 4: Add Services X-Git-Url: http://juplo.de/gitweb/?a=commitdiff_plain;h=ef15a90ba71bcff7765f089af11e2ad22752a352;p=examples%2Fangular-tour-of-heroes 4: Add Services a) Create the HeroService + Provide the HeroService + Update HeroesComponent --- diff --git a/src/app/hero.service.spec.ts b/src/app/hero.service.spec.ts new file mode 100644 index 0000000..082791a --- /dev/null +++ b/src/app/hero.service.spec.ts @@ -0,0 +1,12 @@ +import { TestBed } from '@angular/core/testing'; + +import { HeroService } from './hero.service'; + +describe('HeroService', () => { + beforeEach(() => TestBed.configureTestingModule({})); + + it('should be created', () => { + const service: HeroService = TestBed.get(HeroService); + expect(service).toBeTruthy(); + }); +}); diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts new file mode 100644 index 0000000..7e0771a --- /dev/null +++ b/src/app/hero.service.ts @@ -0,0 +1,16 @@ +import { Injectable } from '@angular/core'; +import { Hero } from './hero'; +import { HEROES } from './mock-heroes'; + + +@Injectable({ + providedIn: 'root' +}) +export class HeroService { + + constructor() { } + + getHeroes() : Hero[] { + return HEROES; + } +} diff --git a/src/app/heroes/heroes.component.ts b/src/app/heroes/heroes.component.ts index a09ff13..94f4266 100644 --- a/src/app/heroes/heroes.component.ts +++ b/src/app/heroes/heroes.component.ts @@ -1,6 +1,6 @@ import { Component, OnInit } from '@angular/core'; import { Hero } from '../hero'; -import { HEROES } from '../mock-heroes'; +import { HeroService } from '../hero.service'; @Component({ selector: 'app-heroes', @@ -9,7 +9,7 @@ import { HEROES } from '../mock-heroes'; }) export class HeroesComponent implements OnInit { - heroes = HEROES; + heroes: Hero[]; selectedHero : Hero; @@ -17,9 +17,13 @@ export class HeroesComponent implements OnInit { this.selectedHero = hero; } - constructor() { } + constructor(private heroService : HeroService) { } ngOnInit() { + this.getHeroes(); } + getHeroes() : void { + this.heroes = this.heroService.getHeroes(); + } }