0

I am trying to map the response from an API and put it in html. Here are the main classes

app.component.html

<h1>sneaky calories work!!</h1>
your query is {{recipeResult.q}}
<div *ngFor = "let recipeIn of recipeResult.hits">
    {{recipeIn.label}} {{recipeIn.url}}
<div>

app.component.ts

import { Component } from '@angular/core';
import { SearchRecipeService } from './recipe-service.service';
import { RecipeGlobal } from './pojos/recipe';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'SnearkyCalories';
  recipeResult: RecipeGlobal;
  constructor(private searchRecipeService: SearchRecipeService){}

  ngOnInit(){
    this.getRecipeInfo();
    console.log(this.recipeResult.hits);
  }

  getRecipeInfo(){
    this.searchRecipeService.getRecipeInfo().
    subscribe(recipeResult => this.recipeResult = recipeResult);
 }
}

Recipe.ts:

export interface RecipeGlobal {
    q:     string;
    from:  number;
    to:    number;
    more:  boolean;
    count: number;
    hits:  Hit[];
}

export interface Hit {
    recipe:     Recipe;
    bookmarked: boolean;
    bought:     boolean;
}

export interface Recipe {
    uri:             string;
    label:           string;
    image:           string;
    source:          string;
    url:             string;
    shareAs:         string;
    yield:           number;
    dietLabels:      string[];
    healthLabels:    string[];
    cautions:        any[];
    ingredientLines: string[];
    ingredients:     Ingredient[];
    calories:        number;
    totalWeight:     number;
    totalTime:       number;
    totalNutrients:  { [key: string]: Total };
    totalDaily:      { [key: string]: Total };
    digest:          Digest[];
}

export interface Digest {
    label:        string;
    tag:          string;
    schemaOrgTag: null | string;
    total:        number;
    hasRDI:       boolean;
    daily:        number;
    unit:         Unit;
    sub?:         Digest[];
}

export enum Unit {
    Empty = "%",
    G = "g",
    Kcal = "kcal",
    Mg = "mg",
    Μg = "µg",
}

export interface Ingredient {
    text:   string;
    weight: number;
}

export interface Total {
    label:    string;
    quantity: number;
    unit:     Unit;
}

recipe-service.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable, of} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators'
import { Component, OnInit, Input } from '@angular/core';
import {RecipeGlobal, Recipe} from './pojos/recipe'

@Injectable({
  providedIn: 'root'
})
export class SearchRecipeService {

  constructor(
    private http: HttpClient) {}

    private searchUrl = 'https://api.edamam.com/search?q=bandeja paisa&app_id=xxxx&app_key=xxxxx&from=0&to=3&calories=591-722&health=alcohol-free';

  getRecipeInfo(): Observable<RecipeGlobal>{
         return this.http.get<RecipeGlobal>(this.searchUrl);
  }


}

I am getting this error in the chrome console: Cannot read property 'hits' of undefined

I have tried printing the object directly in console but still get the same error. It seems like hits is not being parsed properly.

Fernando
  • 381
  • 1
  • 5
  • 20
  • 1
    Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – mbojko Feb 20 '20 at 07:32

2 Answers2

0

recipeResult is still undefined when the component is created. You should use the safe navigation operator or use *ngIf:

<div *ngFor="let recipeIn of recipeResult?.hits">

or

<ng-container *ngIf="recipeResult">
  <h1>sneaky calories work!!</h1>
  your query is {{recipeResult.q}}
  <div *ngFor = "let recipeIn of recipeResult.hits">
    {{recipeIn.label}} {{recipeIn.url}}
  <div>
</ng-container>

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
0

The error is simply because you are trying to access recipeResult before it has been returned asynchronously.

ngOnInit(){
  this.getRecipeInfo();
  // ERROR: this.recipeResult hasn't been returned from the service yet
  // console.log(this.recipeResult.hits);
}

getRecipeInfo(){
  this.searchRecipeService.getRecipeInfo().
  subscribe(recipeResult => {
    this.recipeResult = recipeResult);
    // Move here, it will now log correctly after the recipeResult has been returned
    console.log(this.recipeResult.hits);
  })
}

And you also need to handle the null recipeResult in your component with a ? (>= v9) or *ngIf:

<div *ngFor = "let recipeIn of recipeResult?.hits">
    {{recipeIn.label}} {{recipeIn.url}}
<div>

<!-- alternative for < Angular 9 -->
<ng-container *ngIf="recipeResult>
  <div *ngFor = "let recipeIn of recipeResult?.hits">
      {{recipeIn.label}} {{recipeIn.url}}
  <div>
</ng-container>
Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40