From f48ad6f3e3fa28778b2648a505706cc95ee51978 Mon Sep 17 00:00:00 2001 From: Kai Moritz Date: Sat, 16 May 2020 09:30:55 +0200 Subject: [PATCH] 6: Get Data from a Server c) Heroes and HTTP - Get Heroes with HttpClient --- src/app/hero.service.ts | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index 649b856..d44f22f 100644 --- a/src/app/hero.service.ts +++ b/src/app/hero.service.ts @@ -2,6 +2,7 @@ import { Injectable } from '@angular/core'; import { Observable, of, EMPTY } from 'rxjs'; import { Hero } from './hero'; import { HEROES } from './mock-heroes'; +import { HttpClient } from '@angular/common/http'; import { MessageService } from './message.service'; @@ -10,15 +11,19 @@ import { MessageService } from './message.service'; }) export class HeroService { - constructor(private messageService : MessageService) { } + private heroesUrl = 'api/heroes'; // URL to web api - getHeroes() : Observable { - this.messageService.add('HeroService: fetching heroes...'); - return of(HEROES); + constructor( + private http: HttpClient, + private messageService: MessageService) { } + + getHeroes(): Observable { + this.log('fetching heroes...'); + return this.http.get(this.heroesUrl); } getHero(id: number): Observable { - this.messageService.add(`HeroService: requested hero id=${id}`); + this.log(`requested hero id=${id}`); const found: Hero | undefined = HEROES.find(hero => hero.id === id); if (found === undefined) { return EMPTY; @@ -26,4 +31,9 @@ export class HeroService { return of(found); } } + + /** Log a HeroService message with the MessageService */ + private log(message: string) { + this.messageService.add(`HeroService: ${message}`); + } } -- 2.20.1