[英]How to split an Angular service into several services
所以我在 angular 有一個服務,它從應用程序的誕生開始就在增長。 我的意圖是將服務拆分為處理特定邏輯的不同較小服務。
car.service.ts(巨大的服務)
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class CarService {
engine: any
started: boolean;
lights: any;
speed: number;
constructor() { }
// HUGE AMOUNT OF CODE
......
}
-car.service.ts(帶有公共信息)
汽車服務:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class CarService {
engine: any // Shared variable between services
speed: number;
constructor() { }
}
發動機服務:
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
}
}
燈光服務:
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
}
}
所以這里的問題是如何在不同的新服務之間共享通用信息(在 car.service.ts 上),例如全局變量?
我應該在服務之間使用某種 inheritance 嗎? 或者在它們之間的公共模塊中設置一些特殊配置?
如果您的數據是分層的,例如您沒有在LightsService
中使用EngineService
,那么您可以簡單地將一項服務注入另一項服務:
@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
}
}
這樣就不能同時使用LightsService
中的EngineService
和EngineService
中的LightsService
,因為會造成循環引用。
另一種可能的方法是在單個服務中擁有完整的 model(數據,例如引擎、燈光等),並將其注入所有其他“動作”服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.