Home > Software design >  Angular suscribed observable don't showing information on the view
Angular suscribed observable don't showing information on the view

Time:01-06

image of the detail view with console to see the console.log() I'm having troubles making the Tour Of Heroes Angular tutorial work, i'm in the 6 step of the tutorial, getting the data from a server but instead of getting the data from a simulated data server i have a api with nodejs express and mysql.

The problem cames when i try to show the detail of the hero (fetching one by id), all seems to work but the information don't show on the view.

template:

<div *ngIf="hero">
    <h2>{{ hero.name }} Details</h2>
    <div>id: {{hero.id}}</div>
    <div>
        <label for="name">Hero name: </label>
        <input id="name" [(ngModel)]="hero.name" placeholder="name">
    </div>
    <button type="button" (click)="goBack()">go back</button>
</div>

component:

ngOnInit(): void {
    this.getHero();
  }

  getHero(){
    const id = Number(this.route.snapshot.paramMap.get("id"));
    this.heroService.getHero(id).subscribe(hero => {
      this.hero = hero;
      console.log("hero", hero)
    })
  }

service:

  private heroesUrl = 'http://localhost:3300/api/';

  constructor(private MessageService: MessageService, private http: HttpClient) { 
  }

  private log(message: string) {
    this.MessageService.add(`HeroService: ${message}`);
  }
  
  getHeroes(): Observable<Hero[]>{
    this.log('HeroService: fetched heroes');
    return this.http.get<Hero[]>(this.heroesUrl);
  }


getHero(id: number): Observable<Hero> {
  const url = `${this.heroesUrl}${id}`;
  return this.http.get<Hero>(url);
}

I don't know what's the problem, im learning angular but the observable is well suscribed, in the attached image you can see in the console that at least the api is working.

CodePudding user response:

you received an array with an unique element, see the [``] in console. So

Or in subscribe your write hero[0]

  this.heroService.getHero(id).subscribe(hero => {
      this.hero = hero[0];
    })

Or in your service return the first element of the array. For this use rxjs/operator map

getHero(id: number): Observable<Hero> {
  const url = `${this.heroesUrl}${id}`;
  return this.http.get<Hero[]>(url).pipe(
        map((res:Hero[])=>res[0])
      );
}

See that although you say to Angular that getHero return an Observable<Hero> really you got an Observable<Hero[]>. Yes, when we indicate the return of a function this not make "magically" we get the result, only help us to write the code and the editor advise us about it

  • Related