mpunit30
mpunit30

Reputation: 391

How to get the previous route in angular2, so after some processing making the navigation back to previous url

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

Upvotes: 2

Views: 4208

Answers (2)

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(); }

Upvotes: 6

Kay
Kay

Reputation: 19660

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 } 

Upvotes: 1

Related Questions