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

查看:58
本文介绍了如何检测在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.

推荐答案


编辑 请不要这样做.


EDIT Please don't do this.

官方文档说:此类不应由应用程序开发人员直接使用.而应使用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天全站免登陆