How to Use Services in Angular

Angular services are essential for managing and sharing data across different components in your app. Services allow you to separate the logic and data, making your application more modular. Follow these easy steps to create and use services in Angular.

Step 1: Create a New Angular Service

Creating a service in Angular allows you to inject reusable logic across multiple components.

What to do:

  1. Open the terminal in your IDE and navigate to your project directory.
  2. Run the following command to generate a new service called housing:
ng generate service housing --skip-tests
  1. Run ng serve to ensure the app is running at http://localhost:4200 and there are no errors.

Step 2: Add Static Data to the Angular Service

Next, you will add static data to the new service, which will later be replaced with dynamic data from a real API.

What to do:

  1. Open src/app/home/home.component.ts.
  2. Copy the housingLocationList array from the HomeComponent.
  3. Open src/app/housing.service.ts and paste the housingLocationList inside the HousingService class.

Now, add the following two functions to provide access to the data:

getAllHousingLocations(): HousingLocation[] {
  return this.housingLocationList;
}

getHousingLocationById(id: number): HousingLocation | undefined {
  return this.housingLocationList.find(housingLocation => housingLocation.id === id);
}

Don’t forget to import the HousingLocation type at the top of the service file:

import { HousingLocation } from './housinglocation';

Step 3: Inject the Service into the HomeComponent

Now, you’ll inject the HousingService into the HomeComponent to access the data from the service.

What to do:

  1. In src/app/home/home.component.ts, import the necessary items from @angular/core and HousingService:
import { Component, inject } from '@angular/core';
import { HousingService } from '../housing.service';

Replace the housingLocationList with an empty array and update the constructor to pull data from the service:

housingLocationList: HousingLocation[] = [];
housingService: HousingService = inject(HousingService);

constructor() {
  this.housingLocationList = this.housingService.getAllHousingLocations();
}

Save all your changes and ensure your app builds without errors.

In this guide, you’ve learned how to:

  • Create an Angular service to manage reusable data.
  • Add static data to the service and implement functions to retrieve data.
  • Inject the service into a component using Angular’s dependency injection.

This method allows for better data management and ensures that multiple components can access the same service without duplicating logic. In the future, you’ll replace the static data with data from an API, making your Angular app even more dynamic and scalable.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *