0
0
Angularframework~30 mins

Service-based state management in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Service-based State Management in Angular
📖 Scenario: You are building a simple Angular app to manage a list of favorite movies. You want to keep the list of movies in one place so that different parts of your app can access and update it easily.
🎯 Goal: Create an Angular service to hold the list of favorite movies and allow components to add new movies and get the current list.
📋 What You'll Learn
Create a service called MovieService with a private array of movies
Add a method getMovies() that returns the current list of movies
Add a method addMovie(movie: string) to add a new movie to the list
Use Angular's @Injectable decorator with providedIn: 'root'
Create a component that uses MovieService to display and add movies
💡 Why This Matters
🌍 Real World
Service-based state management is common in Angular apps to share data between components without repeating code or using complex state libraries.
💼 Career
Understanding how to create and use services for state management is a key skill for Angular developers working on real-world applications.
Progress0 / 4 steps
1
Create the MovieService with initial movie list
Create a service called MovieService with a private array movies containing these exact strings: 'Inception', 'The Matrix', and 'Interstellar'. Use @Injectable({ providedIn: 'root' }) decorator.
Angular
Need a hint?

Use @Injectable from @angular/core and create a private array called movies with the exact movie names.

2
Add getMovies method to MovieService
Add a public method called getMovies() in MovieService that returns the movies array.
Angular
Need a hint?

Write a method getMovies() that returns the private movies array.

3
Add addMovie method to MovieService
Add a public method called addMovie(movie: string) in MovieService that adds the movie string to the movies array.
Angular
Need a hint?

Write a method addMovie that takes a string and adds it to the movies array using push.

4
Create a component to use MovieService
Create a component class called MovieListComponent that injects MovieService in its constructor. Add a public property movies initialized by calling getMovies() from the service. Add a method addNewMovie(movie: string) that calls addMovie(movie) on the service and updates movies by calling getMovies() again.
Angular
Need a hint?

Create a component class that injects MovieService in the constructor. Initialize movies by calling getMovies(). Add a method addNewMovie that calls addMovie and updates movies.