在打字稿中处理浏览器后退按钮事件

时间:2018-01-05 16:49:11

标签: angular typescript

我有一篇文章的代码。

window.addEventListener('popstate', function (event) {
            // The popstate event is fired each time when the current history entry changes.

            var r = confirm("You pressed a Back button! Are you sure?!");

            if (r == true) {
                // Call Back button programmatically as per user confirmation.
                history.back();
                // Uncomment below line to redirect to the previous page instead.
                // window.location = document.referrer // Note: IE11 is not supporting this.
            } else {
                // Stay on the current page.
                history.pushState(null, null, window.location.pathname);
            }

            history.pushState(null, null, window.location.pathname);

        }, false);

我把这个代码放在角度2的组件中?代码打字稿兼容吗?当我按下按钮时,我无法触发此事件。有没有更好的方法?

2 个答案:

答案 0 :(得分:1)

在角度2中,您可以使用PlatformLocation具有onPopState侦听器。

import { PlatformLocation } from '@angular/common' 

constructor(location: PlatformLocation) {

    location.onPopState(() => {

        var r = confirm("You pressed a Back button! Are you sure?!");

        if (r == true) {
            // Call Back button programmatically as per user confirmation.
            history.back();
            // Uncomment below line to redirect to the previous page instead.
            // window.location = document.referrer // Note: IE11 is not supporting this.
        } else {
            // Stay on the current page.
            history.pushState(null, null, window.location.pathname);
        }

        history.pushState(null, null, window.location.pathname);
    });

}

答案 1 :(得分:0)

您无需在项目中的任何位置添加此代码。 Angular将负责浏览器的后退按钮。