识别Angular2中的后退/前进浏览器按钮

问题描述 投票:1回答:1

我正在编写一个Angular2应用程序,我想从浏览器处理后退和前进按钮。

我们的想法是在控制台中写一条关于“后退”点击的消息和“前进”点击上的不同消息。

我用过这段代码:

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

问题是:我无法识别单击是否向后或向前在控制台中写入正确的消息。

我怎样才能在angular2中检查它?我不知道我应该在google上搜索什么。所有的答案都是要处理这个事件,但要区分它。

附:它适用于我,如果它是在JavaScript中。谢谢。

javascript browser angular2-routing
1个回答
2
投票

我需要区分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 $。

© www.soinside.com 2019 - 2024. All rights reserved.