Activity 23: Research Angular Services

What are Angular Services?

Angular Services are classes that provide a mechanism to share data and logic across different components in an Angular application. They are essential for modularizing code, promoting reusability, and improving the maintainability of the application.

Benefits of Using Angular Services:

  • Code Reusability: Services allow you to write code once and use it across multiple components, reducing redundancy and improving code maintainability.

  • Data Sharing: Services can hold and manage data that needs to be accessible to multiple components, ensuring consistency and data integrity.

  • Business Logic Separation: Complex logic can be encapsulated within services, separating it from component logic, making the code cleaner and easier to understand.

  • Dependency Injection: Angular's dependency injection mechanism makes it easy to inject services into components, simplifying the process of accessing shared functionality and data.

Creating an Angular Service:

To create an Angular service, you can use the Angular CLI:

ng generate component components/student-list

This will generate a new service file named ng generate component components/student-list in your src/app folder. The generated file will have a basic service class structure:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MyServiceService {

  constructor() { }
}

Injecting Services into Components:

To use a service in a component, you need to inject it using the constructor method:

import { Component } from '@angular/core';
import { MyServiceService } from './my-service.service'; // Import the service

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.html',
  styleUrls: ['./my-component.css']
})
export class MyComponent {

  constructor(private myService: MyServiceService) { }

  // Use the service methods
  myMethod() {
    this.myService.someMethod();
  }
}

Example: Data Sharing with a Service

Let's create a service to manage a list of fruits and use it in a component:

1. Create a Service (fruit-list.service.ts):

import { Injectable } from '@angular/core';
import { Fruit } from '../types';

@Injectable({
  providedIn: 'root'
})
export class FruitListService {
  fruitList: Fruit[] = [];

  addFruit(fruit: Fruit) {
    this.fruitList.push(fruit);
  }

  getFruits() {
    return this.fruitList;
  }
}

2. Update the FruitListComponent:

import { Component } from '@angular/core';
import { Fruit } from '../types';
import { FruitListService } from './fruit-list.service'; // Import the service

@Component({
  selector: 'app-fruit-list',
  templateUrl: './fruit-list.component.html',
  styleUrls: ['./fruit-list.component.css']
})
export class FruitListComponent {
  fruitList: Fruit[] = [];
  name: string = '';

  constructor(private fruitListService: FruitListService) { }

  add() {
    this.fruitListService.addFruit({ name: this.name });
    this.name = '';
  }

  ngOnInit() {
    this.fruitList = this.fruitListService.getFruits();
  }
}

3. Update the fruit-list.component.html

<div>
  <input type="text" [(ngModel)]="name" placeholder="Fruit Name">
  <button (click)="add()">Add Fruit</button>
</div>
<ul>
  <li *ngFor="let fruit of fruitList">
    {{ fruit.name }}
  </li>
</ul>

Now, when you add a fruit in the FruitListComponent, the service will store it, and other components can access the updated fruit list through the service.

Research Task: 50 Angular Services

Step-by-Step Outline

  1. Create Services Using Angular CLI:
    Use the Angular CLI to generate services. For each list, you'll create a corresponding service.

     bashCopy codeng generate service student-list
     ng generate service employee-list
     ng generate service fruit-list
    
  1. Define Service Methods:
    Each service will have methods for CRUD operations (Create, Read, Update, Delete) to manage the list data. For example, for student-list.service.ts, you’ll define methods like getStudents(), addStudent(), etc.

  2. Inject Services into Components:
    Each service will be injected into corresponding components (e.g., StudentListComponent, EmployeeListComponent, etc.) to manage and display the list data.

  3. Test the Services:
    Test the services by injecting them into your component spec files to ensure they work as expected.

Example Angular Service Code Snippets

1. StudentListService

A service to manage a list of students.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class StudentListService {
  private students: string[] = [];

  getStudents() {
    return this.students;
  }

  addStudent(student: string) {
    this.students.push(student);
  }

  removeStudent(student: string) {
    this.students = this.students.filter(s => s !== student);
  }
}

2. EmployeeListService

A service to manage a list of employees.

typescriptCopy codeimport { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class EmployeeListService {
  private employees: string[] = [];

  getEmployees() {
    return this.employees;
  }

  addEmployee(employee: string) {
    this.employees.push(employee);
  }

  removeEmployee(employee: string) {
    this.employees = this.employees.filter(e => e !== employee);
  }
}

3. FruitListService

A service to manage a list of fruits.

typescriptCopy codeimport { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class FruitListService {
  private fruits: string[] = [];

  getFruits() {
    return this.fruits;
  }

  addFruit(fruit: string) {
    this.fruits.push(fruit);
  }

  removeFruit(fruit: string) {
    this.fruits = this.fruits.filter(f => f !== fruit);
  }
}

4. BookListService

A service to manage a list of books in a library.

typescriptCopy codeimport { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class BookListService {
  private books: string[] = [];

  getBooks() {
    return this.books;
  }

  addBook(book: string) {
    this.books.push(book);
  }

  removeBook(book: string) {
    this.books = this.books.filter(b => b !== book);
  }
}

5. ProductListService

A service to manage a list of products in a store.

typescriptCopy codeimport { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class ProductListService {
  private products: string[] = [];

  getProducts() {
    return this.products;
  }

  addProduct(product: string) {
    this.products.push(product);
  }

  removeProduct(product: string) {
    this.products = this.products.filter(p => p !== product);
  }