angularangular8angular-routingwindow-object

How to redirect to the previous page in Angular 8


I have a component to which the user can reach from various pages. When the user clicks an OK button in this component, he should be redirected to the previous page ie. the page from where he came to this component.

I came across window.history.back(); and this.router.navigate( '../' ).

Also, what is the difference between window.history.back(); and this.router.navigate( '../' )

I also want to understand what's the difference between this.location.back() and window.history.back().


Solution

  • 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..