用户决定使用@HostListener('window:beforeunload')离开页面后如何执行方法

时间:2019-06-27 13:37:50

标签: angular onbeforeunload

我使用match1 match2 serial1 serial2 group pos (blank) 5 ABC001 ABC002 1 1 1 (blank) ABC002 ABC004 2 2 3 (blank) ABC003 ABC003 1 3 6 (blank) ABC005 ABC006 2 4 7 (blank) ABC007 ABC001 2 5 (blank) 2 ABC004 ABC005 1 6 (blank) 4 ABC006 ABC007 1 7 检测用户是否离开了页面。然后打开一个对话框。如果她离开,我希望触发一个事件(或调用一个方法)。如果用户不离开,则不希望触发此事件。

如果我这样做:

match() = sheetnm1.Range("match_nr").Value 'Here match(a,1) is first argument and match(a,2) is second argument
serial1() = sheetnm1.Range("serial_nr1").Value 
serial2() = sheetnm1.Range("serial_nr2").Value 
group() = sheetnm1.Range("group_nr").Value

For a = 1 To UBound(match, 1)
    If match(a, 2) = Empty Then
        For b = 1 To UBound(serial1, 1)
            If serial2(a, 1) = serial1(b, 1) Then
                If group(b, 1) = 2 Then
                    match(a, 2) = b
                Else
                    match(a, 1) = b
                End If
            End If
        Next b
    End If
Next a
始终调用

For b = 1 To UBound(serial1, 1) If Not Dict1.Exists(serial1(b, 1)) Then Dict1.Add serial1(b, 1), b End If Next b For a = 1 To UBound(match, 1) If Not Dict2.Exists(serial2(a, 1)) Then Dict2.Add serial2(a, 1), a End If Next b 。我想在调用此函数之前了解用户的答案。

如果我阅读了thisthis,这些解决方案似乎也适用于我的情况,但是我看不到它们如何处理用户的选择(不管是离开还是留下),以了解是否函数是否必须调用。

可能与我不在@HostListener('window:beforeunload')中使用的 @HostListener('window:beforeunload') private someFunction() { WHATEVER } 有关吗?​​

1 个答案:

答案 0 :(得分:0)

您可以像这样实现canDeactivate Guard 您可以添加确认以检测用户选择的确定,还是这样取消

canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> 
{
  let confirmObject = confirm("You want to leave ?");
  if (confirmObject  == true) {
    //call some thing then return true;
    return true;
  } 
  else {
    return false;
  }
}

更新,也许您可​​以尝试使用canDeactivate的相同代码

@HostListener('window:beforeunload')
  private someFunction() {
    let confirmObject = confirm("You want to leave ?");
    if (confirmObject  == true) {
      //call some thing then return true;
      return true;
    } 
    else {
      return false;
    }
  }
相关问题