gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:53:53 24 4
gpt4 key购买 nike

我正在编写 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com