I want to implement the redirection functionality where if user is loggin then user needs to go to previous page ex... Page A ----> Login (susccess) ' PageA<------ I have done this by implementing the router event subscribe method but the problem is router event doesnt fire when page is loaded hence my manager suggested me to go with authguard where i am getting the URL of previous page but how to implement it, and once i get the previous URL, i am storing and dispatching the URL from login to further position, basically i need the previous URL on login component.
Below is the sample auth guard :
import {
Injectable
} from '@angular/core';
import {
Router,
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
} from '@angular/router';
import {
LocalStorageService
} from 'ngx-webstorage';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
userSessionId: string | null = null;
URLPath: string | undefined;
constructor(private router: Router, private storage: LocalStorageService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// not logged in so redirect to login page with the return url
this.URLPath = this.router.url.substring(
0,
this.router.url.lastIndexOf('/')
);
debugger
console.log(state.url, "previous **************url*********");
this.router.navigate([this.URLPath + '/login'], {
queryParams: {
returnUrl: state.url
},
});
return false;
}
}
In the above console getting the previous URL the first issue i am facing is auth guard is using can activate state where it will be accessed only for few pages which needs the session token same goes with CANLoad.
Below is the routing.ts
{
path: 'services',
loadChildren: () =>
import ('../services/services.module').then((m) => m.ServicesModule),
canActivate: [AuthGuard],
}, {
path: 'select-employee/:serviceId',
loadChildren: () =>
import ('../employee/employee.module').then((m) => m.EmployeeModule),
canActivate: [AuthGuard],
}, {
path: 'appointments',
loadChildren: () =>
import ('../appointments/appointments.module').then(
(m) => m.AppointmentsModule
),
canActivate: [AuthGuard],
}, {
path: 'review',
loadChildren: () =>
import ('../review/review.module').then((m) => m.ReviewModule),
canLoad: [CanLoadReviewGuard],
canActivate: [AuthGuard],
}, {
path: 'bookings',
loadChildren: () =>
import ('../bookings/bookings.module').then((m) => m.BookingsModule)
}, {
path: 'login',
loadChildren: () =>
import ('src/app/authentication/login/login.module').then((m) => m.LoginModule)
},
in the above for few components already auth guard is implemented i guess i cant create new one and if so i implement the authguard how to get the state.url in login component?
Please help me got stuck in this issue since long