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