angular - 如何检测用户在 Angular2 中导航回来?

标签 angular typescript angular2-routing

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

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

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

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

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

        });

}

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

最佳答案


编辑 请不要这样做。

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


可以使用具有 onPopState 监听器的 PlatformLocation

import { PlatformLocation } from '@angular/common'

(...)

constructor(location: PlatformLocation) {

    location.onPopState(() => {

        console.log('pressed back!');

    });

}

(...)

关于angular - 如何检测用户在 Angular2 中导航回来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40381814/

相关文章:

angular - 如何将日期转换为 Angular 2 中的 'yyyy-MM-dd' 格式

html - 如何从 Angular 7 的组件列表中预先选择默认项

angular - 使用新的 Router v3 Angular2 清除所有 queryParams

javascript - 我怎么能使用 system.import() 到组件 Angular 2

javascript - Swiper.js 分页自定义项目符号不会点击移动到下一张幻灯片

android - AngularJS 2 和 Cordova : "Failed to load resource: net::ERR_FILE_NOT_FOUND"

angular - 当 FormControlName 是动态且可以更改时如何初始化 FormGroup?

javascript - Typescript 错误 TS1005 : ':' expected. 与 Object.assign()

typescript - 在 Typescript 中防止不适当的导入和执行项目层次结构

json - 直接访问 JSON 对象属性并记录它