To get the last successful navigation and navigate to it you can use:
const lastNav = router.getLastSuccessfulNavigation();
const previousRoute = lastNav.previousNavigation;
router.navigateByUrl(previousRoute);
Note: Since previousRoute
is of type UrlTree
you can use it directly to navigate with the navigateByUrl
method..
Regarding history.back (from the docs):
The history.back() method causes the browser to move back one page in the session history. It has the same effect as calling history.go(-1) . If there is no previous page, this method call does nothing
While this.router.navigate( '../' )
will lead you up to higher levels in the navigation using: <a [routerLink]="['../', 'foo', 'bar']">Go Up</a>
So the difference is that window.history.back();
will lead you back and this.router.navigate( '../' )
will lead you up..
Regarding your last question:
The window
object refers to the current frame, which has a history object property that returns the history object for the window -> more Info: https://www.w3schools.com/jsref/obj_history.asp
While location
should be imported from @angular/common
and used in a constructor like:
import {Location} from '@angular/common';
@Component({
// component's declarations here
})
class SomeComponent {
constructor(private location: Location)
{}
goBack() {
this.location.back();
}
}
The goBack()
function can then be invoked by an onClick
on a Go Back button for example..
Have a look at https://angular.io/guide/architecture-components for more details..