Displaying Recipe Details
Introduction: Making the Recipe View Dynamic
In the last lesson, you built the HTML template for the Recipe Detail View in your Cooking Helper app. Right now, your page is still static — it doesn’t show any real recipe data yet.
In this lesson, you’ll focus on using TypeScript in your Angular component to fetch recipe details from your backend and display them on the page. This will make your Recipe View interactive and dynamic, so users can see real recipe information.
By the end of this lesson, you’ll know how to:
- Get recipe data from your backend using
TypeScriptand Angular services - Update the page with the recipe’s title, rating, ingredients, and steps using Angular’s template syntax
- Handle errors if something goes wrong
Fetching Recipe Data from the Backend
The main job of your component’s TypeScript class is to fetch data and provide it to the template. In Angular, you typically use a service to handle HTTP requests. Here’s how you can fetch recipe data and handle loading and error states.
1. Inject the Services
First, inject the ApiService and ActivatedRoute:
This constructor sets up your component to use two services:
ApiServicelets you make HTTP requests to your backend to get recipe data.ActivatedRoutegives you access to information about the current route, such as the recipe ID in the URL. It calls a function calledloadRecipeFromRoute()that we will implement later.
2. Get the Recipe ID from the Route
We call a method in the constructor to subscribe to route changes and fetch the recipe:
- Uses
takeUntilDestroyed(this.destroyRef)to automatically unsubscribe when the component is destroyed. - Calls
this.cdr.markForCheck()after updating state to ensure the UI updates.
