如何检测用户在 Angular2 中导航回来? [英] How do I detect user navigating back in Angular2?

查看:25
本文介绍了如何检测用户在 Angular2 中导航回来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,我需要检测用户是否按下了浏览器中的后退按钮以返回.

I have a component and I need to detect if user pressed back button in his browser to navigate back.

目前我正在订阅路由器事件.

Currently I'm subscribing router events.

constructor(private router: Router, private activatedRoute: ActivatedRoute) {

    this.routerSubscription = router.events
        .subscribe(event => {

            // if (event.navigatesBack()) ...

        });

}

我知道我可以使用 window.onpopstate 但在使用 Angular2 时感觉就像一个黑客.

I know that I can use window.onpopstate but it feels like a hack when using Angular2.

推荐答案


编辑请不要这样做.

官方文档说应用程序开发人员不应直接使用此类.相反,请使用 Location."参考:https://angular.io/api/common/PlatformLocation

The official docs say "This class should not be used directly by an application developer. Instead, use Location." Ref: https://angular.io/api/common/PlatformLocation

可以使用具有 onPopState 侦听器的 PlatformLocation.

It's possible to use PlatformLocation which has onPopState listener.

import { PlatformLocation } from '@angular/common'

(...)

constructor(location: PlatformLocation) {

    location.onPopState(() => {

        console.log('pressed back!');

    });

}

(...)

这篇关于如何检测用户在 Angular2 中导航回来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆