Search⌘ K
AI Features

Classic Pattern for Fetching Data

Explore how to implement a classic data fetching pattern in Angular by defining typed data models and using RxJS observables. Learn to create a reusable service for HTTP data retrieval and efficiently subscribe to data streams, while managing memory with proper unsubscription techniques.

Let’s start by exploring the classic pattern for collecting our data. In our scenario, the requested data is the list of recipes.

Defining the structure of the data

First and foremost, we need to define the structure of our data so that we can strongly type it. We can use the Angular command line interface (CLI) to generate the Recipe model underneath the src/app/core/model folder:

ng g i Recipe

For conventional purposes, we’ll change the name of the generated file from recipe.ts to recipe.model.ts. Then we’ll populate the interface with the specific properties of the Recipe, as follows:

TypeScript 3.3.4
export interface Recipe {
id: number;
title: string;
ingredients: string;
tags?: string;
imageUrl: string;
cookingTime?: number;
prepTime?: number;
yield: number;
steps?: string;
rating: number;
}

One by one, we put the properties of the recipe we’re going to use, followed ...

Creating

...