Skip to content

Instantly share code, notes, and snippets.

@ibhargav90
Created May 7, 2020 14:07
Show Gist options
  • Save ibhargav90/3022e840aafd55abccd7e1a50e63dd3f to your computer and use it in GitHub Desktop.
Save ibhargav90/3022e840aafd55abccd7e1a50e63dd3f to your computer and use it in GitHub Desktop.
import { Injectable, OnDestroy } from '@angular/core';
import { NavigationEnd, Router, RoutesRecognized } from '@angular/router';
import { filter, pairwise } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs';
import { Location } from '@angular/common';
import { CommonUtilsService } from './common-utils.service';
import { untilDestroyed } from './until-destroyed';
import { AppConstants } from '../../app.constants';
@Injectable({
providedIn: 'root'
})
export class RouterEvents implements OnDestroy {
// save the previous route
public previousRoutePath = new BehaviorSubject<string>(this.getPreviousRoutePath());
constructor(
private router: Router,
private location: Location,
private utils: CommonUtilsService
) {
// on every route change take the two events of two routes changed(using pairwise)
// and save the old one in a behavious subject to access it in another component
// we can use if another component like intro-advertise need the previous route
// because he need to redirect the user to where he did came from.
this.router.events
.pipe(
filter((e) => e instanceof RoutesRecognized),
pairwise(),
untilDestroyed(this)
)
.subscribe((event: any[]) => {
this.announcePreviousRoutePath(event[0].urlAfterRedirects);
});
}
announcePreviousRoutePath(path: string) {
this.setPreviousRoutePath(path);
this.previousRoutePath.next(path);
}
private getPreviousRoutePath(): string {
const previousRoutePath = sessionStorage.getItem(AppConstants.ROUTER.PREV_URL);
if (!previousRoutePath) {
return '';
}
console.log('get', this.utils.cryptThis(this.utils.decode(previousRoutePath), 17));
return this.utils.cryptThis(this.utils.decode(previousRoutePath), 17);
}
private setPreviousRoutePath(previousRoutePath: string): void {
const cryptPreviousRoutePath = this.utils.encode(
this.utils.cryptThis(previousRoutePath, 17)
);
console.log('set', previousRoutePath);
sessionStorage.setItem(AppConstants.ROUTER.PREV_URL, cryptPreviousRoutePath);
}
ngOnDestroy(): void {}
}
add this service in parent component, app.component.ts
constructor(private routerEvents: RouterEvents) {}
and use it in where you redirect after login,
login.component.ts
--> this.router.navigate([this.routeEvents.previousRoutePath.value])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment