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

Mic*_*zko 41 typescript angular2-routing angular

我有一个组件,我需要检测用户是否在他的浏览器中按下了按钮以导航回来.

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

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

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

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

        });

}
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*zko 35

有可能使用PlatformLocation哪个有onPopState听众.

import { PlatformLocation } from '@angular/common'

(...)

constructor(location: PlatformLocation) {

    location.onPopState(() => {

        console.log('pressed back!');

    });

}

(...)
Run Code Online (Sandbox Code Playgroud)

  • Angular文档说不直接使用PlatformLocation,而是使用Location. (10认同)
  • [@dream_team评论来源](https://angular.io/api/common/PlatformLocation) (4认同)
  • 你 console.log('pressed back!') 但它也会被前进按钮触发 (4认同)

tho*_*n87 30

IMO更好的持久化popstate事件的方法是订阅位置服务

import {Location} from "@angular/common";

constructor(private location: Location) { }

ngOnInit() {
    this.location.subscribe(x => console.log(x));
}
Run Code Online (Sandbox Code Playgroud)

它不直接使用PlatformLocation(如文档所示),您可以随时取消订阅.

  • 不要忘记在ngOnDestroy()中取消订阅! (8认同)
  • 作为替代方案,您可以订阅 route.params.subscribe(...); 不同之处在于它会在您最初进入页面时触发,而 location.subscribe(...) 不会。后者仅在参数实际更改时触发。 (2认同)
  • @Humppakäräjät *它仅在检测到路由参数已更改时触发,这可能在用户点击浏览器后退或前进按钮时发生。* - 因为它只能**可能工作**它是无用的。 (2认同)

VSO*_*VSO 15

import { HostListener } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)

然后听popstatewindow对象:

  @HostListener('window:popstate', ['$event'])
  onPopState(event) {
    console.log('Back button pressed');
  }
Run Code Online (Sandbox Code Playgroud)

此代码适用于最新的Angular 2.

  • 这对我不起作用.在这种情况下单击后退按钮时不会触发任何事件. (3认同)
  • 您如何确定它是由“后退”还是“前进”触发的? (3认同)