Maybe you'd like to check if the previous point of history is within your app. For example, if you enter directly to your app and do location.back()
(by pressing a <- back
button in a toolbar for example), you'd be back to your browser's main page, instead of going somewhere else within your app.
This is how I check for this:
import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-foo',
template: ''
})
export class FooComponent {
private readonly canGoBack: boolean;
constructor(
private readonly route: ActivatedRoute,
private readonly router: Router,
private readonly location: Location
) {
// This is where the check is done. Make sure to do this
// here in the constructor, otherwise `getCurrentNavigation()`
// will return null.
this.canGoBack = !!(this.router.getCurrentNavigation()?.previousNavigation);
}
goBack(): void {
if (this.canGoBack) {
// We can safely go back to the previous location as
// we know it's within our app.
this.location.back();
} else {
// There's no previous navigation.
// Here we decide where to go. For example, let's say the
// upper level is the index page, so we go up one level.
this.router.navigate(['..'], {relativeTo: this.route});
}
}
}
We check if the navigation that loaded the current route has a previous sibling. This has to be done in the constructor, while the navigation process is still active.
This doesn't come without caveats though:
canGoBack
will be false even if the previous location is actually within our app but the page was refreshed.
- The user might want to "go back" to the previous page (where the
goBack()
ocurred) by clicking the browser's back button, but since the app went back on history instead of pushing a new location, the user will be going back even further and might get confused.