I share hero.service.ts that I used in my 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();
}
}
When I check the heroesUrl(http://localhost:3000/heroes) using Get method in Postman, it returns
[
{ 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' }
]
But in my code, I can't get the desired result. What is wrong in my code? I am finding right answer all day, but I can't find what I want. enter image description here
I added heroes.components.ts file in description.
And catchError(this.handleError<Hero[]>('getHeroes', [])) this part generates undefined.
As I used Nestjs as backend, I tried to use app.enableCors() to enable all CORS, but it is same the result.
Thanks for your all comments.
CORSissue through inspect your code?undefined? How is this segment used?catchError(err=>this.handleError<Hero[]>(('getHeroes', [],error)but I can imagine what is happened