识别Angular2中的背部/向前浏览器按钮



我正在编程Angular2应用程序,我想从浏览器中处理背部和前方按钮。

这个想法是在"向后"单击"向前"上单击"向后"上的消息上写下消息。

我使用了此代码:

import { Location } from '@angular/common';
export class AppComponent implements OnInit {
   constructor(private location: Location) {}
    ngOnInit() {
       this.location.subscribe(x => { [custom message]  });
    }
}

问题是:如果单击是返回或向前返回的单击以在控制台中写入正确的消息,我将无法识别单击。

如何在Angular2中检查它?我不知道应该在Google上搜索什么。所有的答案都将处理事件,但要区分事件。

P.S。如果在JavaScript中,它对我有用。谢谢。

我还需要在Angular(5)中区分背部和前方按钮(在我的情况下,都可以使路线过渡动画。我找不到解决方案,所以这是我想到的。

将以下内容添加到服务中。

private popState: boolean = false;
private urlHistory: string[] = [];
private popSubject: Subject<boolean> = new Subject();
constructor(private location: Location, private router: Router) {
    location.subscribe(event => {
        let fwd = false;
        if (this.urlHistory.lastIndexOf(event.url)) {
            this.urlHistory.push(event.url);
        }
        else {
            fwd = true;
            this.urlHistory.pop();
        }
        this.popState = true;
        this.popSubject.next(fwd);
    })
    router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
            if (!this.popState)
                this.urlHistory = [this.router.url];
            this.popState = false;
        }
    })
}
get popEvent$() {
    return this.popSubject.asObservable();
}

导入:

import { Location } from '@angular/common';
import { NavigationEnd, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

如果您不需要外部收听事件,请删除PopSubject和Popevent $。

最新更新