Problem pulling data from NASA API service

Data comes from the NASA API service. But I can’t list them. Can someone help me?

My code;

nasa.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class NasaService {
  public apiUrl: any = 'https://api.nasa.gov/planetary/apod';
  public apiKey: any = '?api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

  constructor(private http: HttpClient) { }

  getImage() {
    console.log('Image Loaded');
    const url = this.apiUrl + this.apiKey;
    return this.http.get(url);
  }
}

tab3.page.ts

import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { NasaService } from '../nasa.service';

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss']
})
export class Tab3Page {

  data: any = [];

  constructor(private nasaService: NasaService, private http: HttpClient, private router: Router) {}

  ngOnInit() {
    this.nasaService
    .getImage()
    .subscribe(data =>{
      console.log(data);
      this.data = data;
    });
  }
}

tab3.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>
      Astronomy Picture of Day
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
    <ion-item *ngFor="let result of data.{I don't know what to write here.}">
      <h1>{{result.title}}</h1>
      <ion-img [src]="result.url"></ion-img>
      <h4>{{result.date}}</h4><br>
      <ion-label>{{result.explanation}}</ion-label>
    </ion-item>
</ion-content>

API Result

dasdasd

I think it’s worth the time and effort to define interfaces for everything in your app. You should almost never need any in an Ionic app, to the point where it should make you somewhat physically ill when you type that word.

interface PictureOfTheDay {
  service_version: "v1" | "v2";
  copyright?: string;
  date: Date;
  title: string;
  explanation: string;
  media_type: "image" | "video";
  url: string;
  hdurl: string;
}

(the declarations of service_version and media_type are arbitrary, intended to show how to write enums in TypeScript)

Now, you can write:

getImage(): Observable<PictureOfTheDay> {
  return this.http.get<PictureOfTheDay>(url);
}
potd$: Observable<PictureOfTheDay>;

constructor(nasaService: NasaService) {
  this.potd$ = nasaService.getImage();
}

Now your IDE can take over and tell you what to write in the template (no ngFor, because you aren’t getting an array, as far as I can see):

<ng-container *ngIf="(potd$ | async) as potd">
  <ion-item>
    <h1 [innerText]="potd.title"></h1>
    <ion-img [src]="potd.url"></ion-img>
    <h4 [innerText]="potd.date"></h4>
    <ion-label [innerText]="potd.explanation"></ion-label>
  </ion-item>
</ng-container>
1 Like

Can you tell me where to write this codes?
(Note: I am writing with Angular.)