Yes, I would do it this way:
@Injectable() // do not forget to register this class as a provider
export class PreviousRouteRecorder implements CanDeactivate {
constructor(private router: Router) {
}
canDeactivate(component: any): Observable | boolean {
localStorage.setItem('previousRoute', this.router.url);
return true;
}
}
export const ROUTES: Routes = [
{
path: 'first',
component: FirstComponent,
canDeactivate: [PreviousRouteRecorder]},
{
path: 'second',
component: SecondComponent
}
];
export class SecondComponent implements OnInit {
ngOnInit(){
console.log(localStorage.getItem('previousRoute'));
}
}