Mic*_*zko 41 typescript angular2-routing angular
我有一个组件,我需要检测用户是否在他的浏览器中按下了按钮以导航回来.
目前我正在订阅路由器事件.
constructor(private router: Router, private activatedRoute: ActivatedRoute) {
this.routerSubscription = router.events
.subscribe(event => {
// if (event.navigatesBack()) ...
});
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用,window.onpopstate但在使用Angular2时感觉就像是黑客.
Mic*_*zko 35
有可能使用PlatformLocation哪个有onPopState听众.
import { PlatformLocation } from '@angular/common'
(...)
constructor(location: PlatformLocation) {
location.onPopState(() => {
console.log('pressed back!');
});
}
(...)
Run Code Online (Sandbox Code Playgroud)
tho*_*n87 30
IMO更好的持久化popstate事件的方法是订阅位置服务
import {Location} from "@angular/common";
constructor(private location: Location) { }
ngOnInit() {
this.location.subscribe(x => console.log(x));
}
Run Code Online (Sandbox Code Playgroud)
它不直接使用PlatformLocation(如文档所示),您可以随时取消订阅.
VSO*_*VSO 15
import { HostListener } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)
然后听popstate上window对象:
@HostListener('window:popstate', ['$event'])
onPopState(event) {
console.log('Back button pressed');
}
Run Code Online (Sandbox Code Playgroud)
此代码适用于最新的Angular 2.
| 归档时间: |
|
| 查看次数: |
50685 次 |
| 最近记录: |