除了在角度中使用接口之外,如何解决循环依赖性

问题描述 投票:0回答:1

A组份

age = 5;

updateAge(){
    this.age++;
}

openpopup(){
    this.window.open({
        title:info,
        content: B_Component
    })
}

组件B

constructor(private a: A_Compoennt){

}
clickButton(){
    this.a.updateAge();
}

我有两个组件,组件A和B,在这两个组件之间没有父/子关系。在这两个组件之间存在循环依赖问题。没有界面我该如何解决这个问题。当我在线检查时,所有帖子都说使用接口来解决循环依赖。

javascript angular typescript circular-dependency
1个回答
0
投票

使用共享服务可以轻松完成您的工作,请查看以下代码段:

common.service.ts

  @Injectable({
      providedIn: 'root'
    })
    export class CommonService {
      age = 5;
      updateAge(){
    this.age++;
      }
    }

ComponentA:

    export class ComponentA {
        constructor(private brodcaster: CommonService){          
         this.brodcaster.updateAge();
        }
}

ComponentB:

    export class ComponentA {
        constructor(private brodcaster: CommonService){
         this.brodcaster.updateAge();
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.