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

时间:2016-11-02 13:59:19

标签: angular typescript angular2-routing

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

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

Jobj = new JSONObject();
Jobj.put("user interactions", "Learning game applications"); 
EventHandler<MouseEvent> handler = event -> {
        event.getSceneX();
        event.getSceneY();
        java.util.Date date = new java.util.Date();

        JSONArray list = new JSONArray();
        list.add(new Timestamp(date.getTime()));
        list.add(event.getSceneX());
        list.add(event.getSceneY());
        Jobj.put("Mouse Events", list);

    };

我知道我可以使用constructor(private router: Router, private activatedRoute: ActivatedRoute) { this.routerSubscription = router.events .subscribe(event => { // if (event.navigatesBack()) ... }); } ,但在使用Angular2时感觉就像是黑客。

6 个答案:

答案 0 :(得分:30)

可以使用PlatformLocation具有onPopState侦听器。

import { PlatformLocation } from '@angular/common'

(...)

constructor(location: PlatformLocation) {

    location.onPopState(() => {

        console.log('pressed back!');

    });

}

(...)

答案 1 :(得分:23)

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

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

constructor(private location: Location) { }

ngOnInit() {
    this.location.subscribe(x => console.log(x));
}

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

答案 2 :(得分:14)

import { HostListener } from '@angular/core';

然后在popstate对象上收听window

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

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

答案 3 :(得分:2)

角度8 +

constructor(private readonly route: Router) {
this.route.events
  .pipe(filter((event) => event instanceof NavigationStart))
  .subscribe((event: NavigationStart) => {
    if (event.restoredState) {
      this.isBackUrl = true;
    }
  });

}

答案 4 :(得分:0)

由于thorin87的回答不使用PlatformLocation。我们需要订阅取消订阅。

import {Subscription} from 'rxjs/Subscription';    

ngOnInit() {
  this.subscription = <Subscription>this
    .location
    .subscribe(() => x => console.log(x));
}

ngOnDestroy() {
  this.subscription.unsubscribe();
}

答案 5 :(得分:-2)

此解决方案适用于所有Angular版本。

import { PlatformLocation } from'@angular/common';

constructor( private _location: PlatformLocation ) {

this._location.onPopState (() => {
 `enter code here` // You could write code to display a custom pop-up here.

 // window.location.href = 'https://www.google.com'; //Navigate to another location when the browser back is clicked.


});