Search⌘ K
AI Features

Reactive Pattern for Fetching Data

Explore the reactive pattern for fetching data in Angular applications using RxJS. Learn to declare observable data streams, utilize the async pipe for automatic subscription management, and avoid manual unsubscriptions. This lesson helps you handle data streams efficiently, improving code clarity and memory management.

The idea behind the reactive pattern for managing unsubscriptions is to keep and use the observable as a stream throughout the application. Don’t worry, this will become more apparent to you later in this section.

Retrieving data as streams

So instead of defining a method to retrieve our data, we’ll declare a variable inside our service in the src/app/core/services/recipes.service.ts file.

TypeScript 3.3.4
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { Recipe } from "../model/recipe";
import { environment } from "src/environments/environment";
const BASE_PATH = environment.basePath;
@Injectable({
providedIn: "root",
})
export class RecipesService {
recipes$ = this.http.get<Recipe[]>(`${BASE_PATH}/recipes`);
constructor(private http: HttpClient) {}
}

Here, we’re declaring the ...