0

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.

5
  • 1
    Please check whether it's CORS issue through inspect your code? Commented Nov 17, 2020 at 3:26
  • 1
    Where does it say undefined? How is this segment used? Commented Nov 17, 2020 at 3:39
  • 1
    Information is missing, share the code where you actually call the getHeroes() function. Commented Nov 17, 2020 at 5:33
  • 1
    I think that should be catchError(err=>this.handleError<Hero[]>(('getHeroes', [],error) but I can imagine what is happened Commented Nov 17, 2020 at 7:17
  • Thank you, guys. It was CORs problem. I used Nestjs server and I added app.enableCors(); in main.ts as guided in docs.nestjs.com/security/cors It's simple solution. Thanks again. Commented Apr 8, 2021 at 7:38

1 Answer 1

1

I could solve this issue. It was CORS error. I used Nestjs server and I added the following code in main.ts

app.enableCors();

It is simple. Thank you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.