首页 > 解决方案 > 调用服务打开一个对话框取决于 setTimeout

问题描述

嗨,由于我是 angular 4 的新手,我遇到了一些问题,例如“未捕获的错误:无法解析所有参数”或循环依赖。我编写了一个服务来进行计算,并在 setTimeout 中调用以打开 MatDialog 。Matdialog 在单击“是”时有两个选项“是”或“否”,进行一些服务调用并进行一些计算,然后再次设置 clearTimeout 并设置新的 setTimeout,一段时间后再次打开弹出窗口。

而且我还想检查每个服务调用,并根据某些情况再次 clearTimeout 并设置一个新的 setTimeout 来打开 MatDialog 。

我尝试了很长时间,但找不到解决方案。我想知道我可以放置代码的正确位置以及如何编写服务以打开 Matdialog 。

在 main.components.ts 中编写了这段代码

setTimer() {

    this.notifyTime = expiryValue - 120000;
    this.date1 = new Date();
    this.date2 = new Date(this.notifyTime);
    this.diff = this.date2.getTime() - this.date1.getTime();
    let _self = this;
    this.timerVar = setTimeout(function () {
        let dialogRef = _self.dialog.open(DialogModalComponent, {
            data: {
                timer: _self.timerVar,
                va: true
            }
        });
    }, this.diff);
}


clearTimer() { 
    clearTimeout(this.timerVar);
}

以上是我用于 setTimeout() 和 clearTimeout() 的一段代码

在全局服务中编写此代码,其中 temp 指向另一个 main.component.ts

autoLoad() {

    if (this.expiryValue) {
        this.date1 = new Date();
        this.diff = this.expiryValue - this.date1.getTime();
        if (this.diff < 600000 && this.diff > 120000) {
            this.getUpUrl('refresh').then(result => {
                if (result.status == 'success') {
                    this.temp.clearTimer();
                    this.temp.showDialog(result.sessionExpiry);
                } 
            });
        }
    }

而在 dialog.component.ts

 ok() {
    this.dialog.close();
    this.temp.clearTimer();
    this.temp.setTimer();
 }

cancel() {
    this.dialog.close();
}

我在对话框中使用的上述代码。temp 指向我的 main.component.ts

标签: javascriptangular

解决方案


您可以使用setTimeout函数在一段时间后打开一个对话框

此示例基于角材料示例

  constructor(public _dialogService: DialogService) { }

  openDialog(): void {
    this.clicked = true;
    this._dialogService.open({ name: this.name, animal: this.animal }, () => this.clicked = false)
      .then(result => {
        console.log('The dialog was closed');
        this.animal = result;
      })
  }

对话服务

@Injectable({
  providedIn:'root'
})
export class DialogService {

  constructor(private dialog: MatDialog) { }

  open(data , onOpenCallBack , timeout:number = 2500) : Promise<any> {
    return new Promise((resolve) => {

    setTimeout(() => {

      const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
        width: '250px',
        data: data
      });

      if (onOpenCallBack) {
        onOpenCallBack()
      }

      dialogRef.afterClosed().subscribe(result => {
        resolve(result)  
      });
    }, timeout)
    })
  }
}

stackblitz 演示


推荐阅读