Search code examples
angularangular-httpclientangular-observable

Angular Observable - Subscribe but html is not outputting the info


I am trying to understand why my API call is giving me an error and won't display the list in HTML? When I tried to debug it the first time around. It is telling me that the "rovers: IRover[];" is undefined. If I have a button that call getRovers(), when I debug it, I can see the array of info from the json. Please see attached for the error message.

Error Message From Browser

1) rover.ts

export interface IRover {
    id: number,
    name: string
}

2) rovers.component.ts

import { Component, OnInit } from '@angular/core';
import { IRover } from './rover';
import { RoversService } from './rovers.service';

@Component({
  selector: 'app-rovers',
  templateUrl: './rovers.component.html',
  styleUrls: ['./rovers.component.css'],
  providers: [RoversService]
})
export class RoversComponent implements OnInit {

  rovers: IRover[];

  constructor(private roversService: RoversService) {}

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

  getRovers(): void {
    this.roversService.getRovers().subscribe(rovers => (this.rovers = rovers));
  }

}

3) rovers.service.ts

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { IRover } from './rover';
import { Injectable } from '@angular/core';

@Injectable()
export class RoversService {
    roversUrl = 'https://api.nasa.gov/mars-photos/api/v1/rovers?api_key=PRIVATEKEY';

    constructor(private http: HttpClient) {}

    /**GET rovers from nasa api */
    getRovers(): Observable<IRover[]> {
        return this.http.get<IRover[]>(this.roversUrl);
    }
}

4) rovers.component.html

<p>rovers works!</p>

<div *ngFor="let rover of rovers">
    <div>
        {{rover.id}} : {{rover.name}}
    </div>
</div>

Solution

  • Looks like your API responds with an object instead of an array.

    Angular ngFor only supports iterating over arrays.

    You will need to convert your response someway to an array.