简体   繁体   中英

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)

  • *engine.service.ts
  • *lights.service.ts

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?

If your data is hierarchical, eg 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 eg engine, lights etc) in a single service and inject it to all other "action" services.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM