Sharing my hero.service.ts
file that was utilized in a recent project:
// hero.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { Hero } from './hero';
import { MessageService } from './message.service';
@Injectable({
providedIn: 'root'
})
export class HeroService {
private heroesUrl = 'http://localhost:3000/heroes';
constructor(private http: HttpClient, private messageService: MessageService) { }
getHeroes(): Observable<Hero[]> {
this.messageService.add('HeroService: fetched heroes');
return this.http.get<Hero[]>(this.heroesUrl).pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}
private log(message: string) {
this.messageService.add(`HeroService: ${message}`);
}
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
}
}
}
// hero.ts
export interface Hero {
id: number;
name: string;
}
// heroes.component.ts
import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
import { MessageService } from '../message.service';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
heroes: Hero[];
constructor(private heroService: HeroService) {
}
getHeros(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
ngOnInit(): void {
this.getHeros();
}
}
After checking the
heroesUrl(http://localhost:3000/heroes)
using Postman's Get method, the following data is returned:
[
{ id: 11, name: 'Dr Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' }
]
However, despite implementing the code, the desired results are not being obtained. Seeking assistance to identify the issue with the provided code which has been under investigation all day long without success.
For details, view image here.
In addition, the inclusion of the heroes.components.ts
file within the description points out that the
catchError(this.handleError<Hero[]>('getHeroes', []))
section leads to an issue where it produces undefined
. Despite attempting the use of app.enableCors()
in Nestjs backend, the outcome remains unchanged. Grateful for any insights or suggestions offered.