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

标签 javascript browser angular2-routing

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

这个想法是在控制台中在“后退”单击时写入一条消息,在“前进”单击时写入不同的消息。

我使用了这段代码:

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

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

如何在 angular2 中检查它?我不知道我应该在谷歌上搜索什么。所有答案都是为了处理该事件,但为了区分它。

附注如果它是用 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$。

关于javascript - 识别 Angular2 中的后退/前进浏览器按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47676400/

相关文章:

javascript - 获取两组字符之间的单词

javascript - 如何在另一个jquery文件中调用jquery方法

html - 在输入字段中显示密码和用户名?

javascript - 桌面通知中的自定义/样式标题和正文方向(chrome)

带有加载指示器的 Angular 2 解析器

javascript - Knockoutjs 中的数字输入和范围 valueUpdate

html - CSS 代码帮助居中图像,但它以某种方式恢复到当前编码的左侧

angular - 在 Angular2 中重定向到 @CanActivate 中的另一个组件

typescript - Angular2 RouterLink 通过用 %2F 替换斜杠来中断路由

javascript - chrome jquery 中的 "input"事件未触发