解决 Angular 9 中不可避免的强制性循环依赖

Addressing a mandatory unavoidable circular dependency in Angular 9

我需要从 UI 端执行会话超时。以下是步骤。

  1. 成功登录后,我开始超时显示弹出窗口 setTimeout(()=>{this.openTimeOutDialog();},expTime);

  2. 1 小时后,出现超时弹出窗口,要求用户注销或保持连接。我在这里设置了另一个超时 5 分钟,在此期间用户应单击保持连接,否则他们将被注销。 setTimeout(()=>{this.logout();},时间);

  3. 如果用户点击保持连接,我需要从创建循环依赖的 TimeOutDialog 组件再次调用这个第一个 setTimeout。即当用户点击保持连接时,调用将转到第一个 setTimeout,然后从那里再次调用相同的 TimeOutDialog。 我尝试了各种方法,但存在这种依赖性。 我看不到避免这种循环依赖的方法。需要帮助解决这个问题。谢谢! 这是我的代码

    //登录服务码


    Import {TimeOutDialog} from './../../timeout/timeout.component';
    Import {LogoutService} from './../logout.service';
    Import{MatDialog} from '@angular/material/dialog';
    
    constructor(private logoutService: LogoutService, public dialog: MatDialog ){}
    
    export class LoginService{
    
    login(uid, pwd){
    .........
    .........
    this.setSessionTimer(expTime);
    }
    
    setSessionTimer(expTime){
    setTimeout(()=>{this.openTimeOutDialog();},expTime);
    }
    
    openTimeOutDialog(){
    setTimeout (()=>{this.logoutService.logout();}, time);
    this.dialog.open(timeoutDialog, {width: '500px'});
    }
    ```


//Logout Service code

    ```
    Export class LogoutService{
    ```logout(){
    ............
    ............
    }
    }
       

//Dialog Component code
Import {LoginService}from './../../services/login.service;
Import {LogoutService}from './../../services/logout.service;
Import {MatDialogRef} from '@angular/material/dialog';

constructor(private logoutService: LogoutService, private loginService: LoginService ){}

Export TimeOutDialog{
stayConnected(){
this.loginService.setSessionTimer(expTime);
}

logout(){
this.logoutService.logout();
}
}

在这种情况下,您可以关闭对话并在必要时启动计时器

 openTimeOutDialog(){
    setTimeout (()=>{this.logoutService.logout();}, time);
    this.dialog.open(
      timeoutDialog, 
      {width: '500px'}
    )
    .afterClosed()
    .subsribe(
       response => { if(response.startSession) {this. setSessionTimer() } }
    )

 }

afterClosed 方法的响应来自对话框

像这样 Modal.component.ts

export class ModalComponent implements OnInit {

  constructor(
    public modalRef: MatDialogRef<ModalComponent, ModalOutputData>,
    @Inject(MAT_DIALOG_DATA) public data: DefaultModalInputData
  ) { }

  ngOnInit() {
    console.log(this.data, 'data');
  }

  /**
   * close dialog and continue
   *
   * @param null
   *
   * @return `void`
   */
  onContinue() {
    this.modalRef.close({ startSession: true }); 
  }
}