2

I have a page with option of wishlist, now if user is not logged in and clicks the wishlist button then user is redirected login page, but after successful user login i want to take user to previous routing state where user clicked the wishlist button ??

I tried using router events like RoutesRecognized but this is not getting fired up first time if i visit the login page second time it fires up. Any suggestions than please do help.

I even used pairwise() method of router events but this also fires second time not first time, that is if i go back to page 1 and re navigate to page2, this method fires up. It simply not getting fired up on first visit from page 1 -> page 2

mpunit30
  • 381
  • 9
  • 26
  • Possible duplicate of [How to go back last page in Angular 2](https://stackoverflow.com/questions/35446955/how-to-go-back-last-page-in-angular-2) – AT82 Oct 13 '17 at 12:24

2 Answers2

6

To implement the most reliable way to go back to previous view in Angular you have to:

  • import { Location } from '@angular/common;

  • Inject location on component constructor:

    constructor( private _location: Location ) {}

  • Call back() method on desired function:

    public goBack() { this._location.back(); }

1

You can use angulars RouterStateSnapshot https://angular.io/api/router/RouterStateSnapshot.

import { RouterStateSnapshot } from '@angular/router';

constructor(state: RouterStateSnapshot) { }

this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } 
Kay
  • 17,906
  • 63
  • 162
  • 270
  • 1
    using this throws me error No provider for RouterStateSnapshot!! So i am using this const snapshot: RouterStateSnapshot = router.routerState.snapshot; but this gives me only the current route state not previous. According to you where should i keep my code ?? – mpunit30 Oct 13 '17 at 10:29