Ik heb een component en ik moet detecteren of de gebruiker op de terugknop in zijn browser heeft gedrukt om terug te navigeren.
Momenteel abonneer ik me op routergebeurtenissen.
constructor(private router: Router, private activatedRoute: ActivatedRoute) {
this.routerSubscription = router.events
.subscribe(event => {
// if (event.navigatesBack()) ...
});
}
Ik weet dat ik window.onpopstate
kan gebruiken, maar het voelt als een hack bij het gebruik van Angular2.
Antwoord 1, autoriteit 100%
BEWERKEN
Doe dit alsjeblieft niet.
In de officiële documenten staat: “Deze klasse mag niet rechtstreeks door een applicatieontwikkelaar worden gebruikt. Gebruik in plaats daarvan Locatie.” Ref: https://angular.io/api/common/PlatformLocation
Het is mogelijk om PlatformLocation
te gebruiken met een onPopState
luisteraar.
import { PlatformLocation } from '@angular/common'
(...)
constructor(location: PlatformLocation) {
location.onPopState(() => {
console.log('pressed back!');
});
}
(...)
Antwoord 2, autoriteit 91%
IMO een betere methode om naar popstate-evenementen te luisteren, is door je te abonneren op locatieservice
import {Location} from "@angular/common";
constructor(private location: Location) { }
ngOnInit() {
this.location.subscribe(x => console.log(x));
}
Het gebruikt PlatformLocation niet rechtstreeks (zoals de documentatie suggereert) en je kunt je op elk gewenst moment uitschrijven.
Antwoord 3, autoriteit 50%
import { HostListener } from '@angular/core';
en luister dan naar popstate
in het window
object:
@HostListener('window:popstate', ['$event'])
onPopState(event) {
console.log('Back button pressed');
}
Deze code werkt voor mij op de nieuwste Angular 2.
Antwoord 4, autoriteit 9%
Als antwoord van Thorin87, gebruik PlatformLocation niet. We moeten inschrijven en afmelden.
import {Subscription} from 'rxjs/Subscription';
ngOnInit() {
this.subscription = <Subscription>this
.location
.subscribe(() => x => console.log(x));
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
Antwoord 5, autoriteit 7%
in hoekig 8+
constructor(private readonly route: Router) {
this.route.events
.pipe(filter((event) => event instanceof NavigationStart))
.subscribe((event: NavigationStart) => {
if (event.restoredState) {
this.isBackUrl = true;
}
});
}
Antwoord 6
Deze oplossing werkt voor alle versies van Angular.
import { PlatformLocation } from'@angular/common';
constructor( private _location: PlatformLocation ) {
this._location.onPopState (() => {
`enter code here` // You could write code to display a custom pop-up here.
// window.location.href = 'https://www.google.com'; //Navigate to another location when the browser back is clicked.
});