Angular服务通过相同的接口/抽象类调用服务 => 循环依赖
创始人
2024-10-25 00:30:50
0次

在Angular中,如果两个服务之间存在循环依赖,可以通过以下步骤来解决:

  1. 创建一个新的接口或抽象类,并将两个服务的共享方法和属性定义在该接口或抽象类中。
// shared.interface.ts
export interface SharedServiceInterface {
  commonMethod(): void;
  commonProperty: string;
}
  1. 在每个服务中分别实现该接口或抽象类,并在构造函数中注入另一个服务。
// service1.service.ts
import { Injectable } from '@angular/core';
import { SharedServiceInterface } from './shared.interface';
import { Service2Service } from './service2.service';

@Injectable({
  providedIn: 'root'
})
export class Service1Service implements SharedServiceInterface {
  commonProperty: string;

  constructor(private service2: Service2Service) {
    this.service2.setService1(this);
  }

  commonMethod(): void {
    // Implementation goes here
  }
}
// service2.service.ts
import { Injectable } from '@angular/core';
import { SharedServiceInterface } from './shared.interface';
import { Service1Service } from './service1.service';

@Injectable({
  providedIn: 'root'
})
export class Service2Service implements SharedServiceInterface {
  service1: Service1Service;
  commonProperty: string;

  constructor(private service1: Service1Service) {}

  setService1(service1: Service1Service): void {
    this.service1 = service1;
  }

  commonMethod(): void {
    // Implementation goes here
  }
}
  1. 在模块中将这两个服务注册为提供商。
// app.module.ts
import { NgModule } from '@angular/core';
import { Service1Service } from './service1.service';
import { Service2Service } from './service2.service';

@NgModule({
  providers: [Service1Service, Service2Service]
})
export class AppModule { }

通过以上步骤,两个服务之间可以通过相同的接口/抽象类来调用服务,同时避免了循环依赖的问题。

相关内容

热门资讯

WPK透视版透视挂练习!wpk... WPK透视版透视挂练习!wpk辅助购买,德扑之星ai多功能透视挂工具1)wpk辅助购买辅助插件:进一...
WPK安装透视资料!wepok... WPK安装透视资料!wepoker游戏下载,德州扑克ai多功能透视appwepoker游戏下载是不是...
WPK真假透视方式!wepok... WPK真假透视方式!wepoker辅助透视软件,wpkai多功能透视技巧1、wepoker辅助透视软...
WPK插件透视挂方针!wepo... WPK插件透视挂方针!wepoker有机器人吗,wpkai多功能透视挂脚本1、进入游戏-大厅左侧-新...
WPK多开辅助器总结!德普软件... WPK多开辅助器总结!德普软件,微扑克ai多功能辅助器神器1、每一步都需要思考,不同水平的挑战德普软...
WPK购买辅助器要领!wepo... WPK购买辅助器要领!wepoker代打辅助机器人,aapokerai多功能辅助器技巧1、起透看视 ...
WPK四人透视大纲!wepok... WPK四人透视大纲!wepoker免费脚本咨询,wpkai多功能透视插件1、完成wepoker免费脚...
WPK俱乐部辅助器讲义!wep... WPK俱乐部辅助器讲义!wepoker有透视底牌吗,德州扑克ai多功能辅助器脚本1、操作简单,无需w...
WPK模拟器透视妙招!wpk透... WPK模拟器透视妙招!wpk透视辅助下载,AApokerai多功能透视工具小薇(辅助器软件下载)致您...
WPK真假开挂要领!wpk软件... WPK真假开挂要领!wpk软件是正规的吗,红龙PoKerai多功能开挂神器1、任何wpk软件是正规的...