The App Logic

Find out what logic needs to be implemented for the Food API Ionic application.

Connecting to the spoonacular API

Our NutrientsService class will import the Angular HttpClient module, for making our HTTP calls to the spoonacular service, and the API key environment property we configured in the last section as well as methods for retrieving specific data.

In the src/app/services/nutrients.service.ts file, we make the following changes (highlighted):

Press + to interact
/**
* NutrientsService
*
* This class provides methods for performing the following queries using the Spoonacular API:
*
* 1. Recipes - Find by nutrients
* 2. Recipes - Random
*/
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class NutrientsService {
private apiKey = environment.keys.api.spoonacular;
private nutrients = 'https://api.spoonacular.com/recipes/findByNutrients?';
private random = 'https://api.spoonacular.com/recipes/random?number=10&tags=vegetarian,dessert';
/**
* Creates an instance of NutrientsService
*/
constructor(private http: HttpClient) { }
/**
* Calls the findByNutrients spoonacular API method and returns the result as an observable
*/
public getRecipesBySpecifiedNutrients(query: string): Observable<any> {
return this.http.get(this.nutrients + query + '&apiKey=' + this.apiKey);
}
/**
* Calls the random spoonacular API method and returns the result as an observable
*/
public getRandomRecipes(): Observable<any> {
return this.http.get(this.random + '&apiKey=' + this.apiKey);
}
}

This is a fairly simple service and is broken down as follows:

  1. Import Angular’s HttpClient module to manage HTTP calls to the spoonacular API on line 10
  2. Import the environment object containing our API key value on line 11
  3. Import the RxJS Observable class to define the return types for our methods on line 12
  4. Define a series of properties for the API key (i.e., apiKey on line 18) and URLs (nutrients and random on lines 19 and 20 respectively) we will be calling
  5. Define two separate methods for calling different spoonacular API routes (or, getRecipesBySpecifiedNutrients and getRandomRecipes on lines 30 and 37 respectively)

Pretty straightforward, right?

The spoonacular API has many different API routes available. In this case study, we’re using only the random and findByNutrients API routes, but feel free to change or add further methods to the NutrientsService.

Since successful HTTP responses from the spoonacular API are returned as an array of JSON objects, we can quickly and easily parse this within our Ionic applications.

Let’s now turn to our HomePage component class and see how this is achieved amongst other aspects of the application logic and functionality.

Tying it together

The ...