致电服务以打开一个对话框,取决于setTimeout

时间:2019-04-01 12:43:55

标签: javascript 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

1 个答案:

答案 0 :(得分:0)

您可以使用 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 demo