创建会话超时功能,可以显示计时器并在超时时以角度重定向到上一页

时间:2018-06-04 06:28:13

标签: javascript angular typescript session routerlink

我想为付款页面创建会话超时功能,其中计时器将显示在我的网页中,5分钟后,付款会话将过期,用户将被重定向到上一页。我使用角度4作为我的前端,因此使用href不受理,我想要一个仅涉及javascriptrouterLink以及typescript的解决方案。有什么建议吗?

我正在使用此功能在网页上显示计时器,其工作但不能在这里使用routerLink重定向到上一页。

paymentSessionTimer() {
let downloadButton = document.getElementById("paymentSession");
var counter = 600;
var newElement = document.createElement("p");
newElement.innerHTML = "10";
var id;
this.redirectFlag = "false";

downloadButton.parentNode.replaceChild(newElement, downloadButton);

id = setInterval(function() {
  counter--;
  if(counter < 0) {
      newElement.parentNode.replaceChild(downloadButton, newElement);
      clearInterval(id);

      this.redirectFlag = "true";     
      //this.router.navigate(['../search']);
  } else {
    newElement.innerHTML = counter.toString() + " seconds left.";  
  }
}, 1000);
this.router.navigate(['../previous']);

}

3 个答案:

答案 0 :(得分:1)

import { Location } from '@angular/common';

timer = {s: 0, mn: 0};

constructor(private location: Location) {
  setTimeout(() => {
    this.location.back();
  }, 300000);

  setInterval(() => {
    this.timer.s += 1;
    if (this.timer.s > 59) {
      this.timer.s = 0;
      this.timer.mn += 1;
    }
  }, 1000);
}

现在您可以显示计时器,并且将重定向用户。

如果你想要一个还原的计时器:

    this.timer.s -= 1;
    if (this.timer.s < 0) {
      this.timer.s = 59;
      this.timer.mn = -1;
    }

答案 1 :(得分:0)

是的,你可以这样做。

在您的组件ts文件中。

select count(*) from products

答案 2 :(得分:0)

使用rxjs timer Observable和一些运算符将是一个干净的解决方案。

您可以创建两个observable(secondsToStringDate函数应该实现,example):

// Fires every second for 5 minutes then completes
sessionExpiration$ = timer(1000).pipe(take(60 * 5));

// Every second, generate a displayable string mm:ss
sessionRemainingTime$ = sessionExpiration$
 .pipe(map(seconds => secondsToStringDate(seconds)));

现在您已经创建了Observable,您可以使用它们:

在时间到期时运行所需的行为:

sessionExpiration$.pipe(finalize(() => {
    // Fired when the sessionExpiration$ observable completes
    // You can put what you want to do when session expires
}).subscribe();

要添加要在模板中显示时间的位置:

<!-- Will display the time in the template --> 
{{sessionRemainingTime$ | async}}

对于安全的解决方案,您应该添加后端解决方案,而不仅仅依赖于javascript。