In my application I created a NavigationService
which contains a flag that can be used to determine if the back button has been pressed.
import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { tap, filter, pairwise, startWith, map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class NavigationService {
wasBackButtonPressed = false;
constructor(private _router: Router) {
this._router.events.pipe(
filter(ev => ev instanceof NavigationStart),
map(ev => <NavigationStart>ev),
startWith(null),
pairwise(),
tap(([ev1, ev2]) => {
if (!ev1 || (ev2.url !== ev1.url)) {
this.wasBackButtonPressed = ev2.navigationTrigger === 'popstate';
}
})
).subscribe();
}
}
It is using Rxjs pairwise()
operator because I noticed that back button causes NavigationStart
event to be sent 2 times, the first one has navigationTrigger = 'popstate'
and that is what we're looking for.
Now I can inject this service into my component, and I can reference this flag to determine whether to run special logic if the user arrived there via the browser's back button.
import { Component, OnInit } from '@angular/core';
import { NavigationService } from 'src/services/navigation.service';
@Component({
selector: 'app-example',
templateUrl: './app-example.component.html',
styleUrls: ['./app-example.component.scss']
})
export class ExampleComponent implements OnInit {
constructor(private _navigationService: NavigationService) {
}
ngOnInit(): void {
if (this._navigationService.wasBackButtonPressed) {
// special logic here when user navigated via back button
}
}
}
One other thing to know is, this NavigationService
should run immediately at app startup, so it can begin working on the very first route change. To do that, inject it into your root app.component
. Full details in this SO post.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…