How do I detect user navigating back in Angular2?
我有一个组件,我需要检测用户是否按下了浏览器中的返回按钮以返回导航。
目前我正在订阅路由器事件。
1
2 3 4 5 6 7 8 9 10 |
constructor(private router: Router, private activatedRoute: ActivatedRoute) {
this.routerSubscription = router.events // if (event.navigatesBack()) … }); } |
我知道我可以使用 window.onpopstate,但是在使用 Angular2 时感觉就像是 hack。
编辑
请不要这样做。
官方文档说”这个类不应该由应用程序开发人员直接使用。相反,使用 Location。”参考:https://angular.io/api/common/PlatformLocation
可以使用具有 onPopState 监听器的 PlatformLocation。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import { PlatformLocation } from ‘@angular/common’
(…) constructor(location: PlatformLocation) { location.onPopState(() => { console.log(‘pressed back!’); }); } (…) |
- 如何在我的 app.module 中导入它。我把这门课放在任何地方都会出错。
- Angular 文档说不要直接使用 PlatformLocation,而是使用 Location。
- 您如何取消订阅此侦听器?
- @KevinLeStarge 你没有。您应该按照 thorin87 的建议使用 Location
- 你 console.log(‘pressed back!’) 但它也会被前进按钮触发
- 实际上,我们所知道的是,我们导航到了历史中的另一个状态。
IMO 更好的监听 popstate 事件的方法是订阅位置服务
1
2 3 4 5 6 7 |
import {Location} from”@angular/common”;
constructor(private location: Location) { } ngOnInit() { |
它不直接使用 PlatformLocation(如文档所示),您可以随时取消订阅。
- 不要忘记取消订阅 ngOnDestroy() !
- 作为替代方案,您可以订阅 route.params.subscribe(…);不同之处在于它会在您初始进入页面时触发,而 location.subscribe(…) 不会。后者仅在参数实际更改时触发。
- @Humppak?r?j?t 这如何帮助判断用户是否向后导航?路由中无法访问history api..
- @Mackelito 是的,您是对的,它不会直接检测到他是否来回。它仅在检测到路由参数已更改时触发,这可能在用户点击浏览器的后退或后退按钮时发生。
- 但这不会发生在任何导航上吗?
- 我不确定它是否会检测上一页是否具有完全相同的 url。但是无论如何你会改变什么;)
- @Humppak?r?j?t 它仅在检测到路由参数已更改时触发,这可能在用户点击浏览器的后退或后退按钮时发生。 – 所以它只能工作它是无用的。
- 它没有为用户导航返回提供解决方案
1
|
import { HostListener } from ‘@angular/core’;
|
然后在 window 对象上监听 popstate:
1
2 3 4 |
@HostListener(‘window:popstate’, [‘$event’])
onPopState(event) { console.log(‘Back button pressed’); } |
此代码适用于我在最新的 Angular 2 上。
- 这对我不起作用。在这种情况下,单击后退按钮时不会触发任何事件。
- 它在 ng-version=”5.2.9″ 上运行良好。简直太棒了!
- 你如何确定它是由后退还是前锋触发的?
作为 thorin87 的答案,不要使用 PlatformLocation。我们需要订阅一个取消订阅。
1
2 3 4 5 6 7 8 9 10 11 |
import {Subscription} from ‘rxjs/Subscription’;
ngOnInit() { ngOnDestroy() { |
angular为 8
1
2 3 4 5 6 7 8 |
constructor(private readonly route: Router) {
this.route.events .pipe(filter((event) => event instanceof NavigationStart)) .subscribe((event: NavigationStart) => { if (event.restoredState) { this.isBackUrl = true; } }); |
}
- 这不会检查导航是向后还是向前。
此解决方案适用于所有版本的 Angular。
1
2 3 4 5 6 7 8 9 10 11 |
import { PlatformLocation } from’@angular/common’;
constructor( private _location: PlatformLocation ) { this._location.onPopState (() => { // window.location.href = ‘https://www.google.com’; //Navigate to another location when the browser back is clicked. }); |
- 官方文档说”这个类不应该由应用程序开发人员直接使用。而是使用位置。”参考:angular.io/api/common/PlatformLocation
来源:https://www.codenong.com/40381814/