Jgascona
Jgascona

Reputation: 1259

How to split an Angular service into several services

So I have a service in angular that is growing from the birth of the application. My intention is to split the service into different smaller services that handle specific logic.

Originally:

car.service.ts (Huge service)

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

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

engine: any
started: boolean;
lights: any;
speed: number;

  constructor() { }

// HUGE AMOUNT OF CODE

 ......

}

GOAL:

-car.service.ts (with common information)

Car service:

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

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

engine: any // Shared variable between services
speed: number;

  constructor() { }

}

Engine service:

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

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

engine: any // Comes in any way from car service
started:boolean;

  constructor() { }

   start() {
   // start the car
   }
}

Lights service:

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

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

engine: any // Comes in any way from car service
lightsOn :boolean;
intensity: number;

  constructor() { }

   turnLights() {
   // turns the lights on/off
   }
}

So the question here is how to share that common information (on car.service.ts) such as global variables between the different new services?

Should I use some kind of inheritance between services? Or maybe set some special configuration in a common module between them?

Upvotes: 0

Views: 414

Answers (1)

kemsky
kemsky

Reputation: 15270

If your data is hierarchical, e.g. you do not use say LightsService in EngineService, then you can simply inject one service into another:

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

engineService: EngineService; // Comes in any way from car service
lightsOn :boolean;
intensity: number;

  constructor(engineService: EngineService) { }

   turnLights() {
   // turns the lights on/off
   }
}

This way it is not possible to use LightsService in EngineService and EngineService in LightsService at the same time because it causes circular references.

Another possible approach is to have full model (data e.g. engine, lights etc) in a single service and inject it to all other "action" services.

Upvotes: 1

Related Questions