Say I have the routing app-routing.module.ts
onst appRoutes: Routes = [
{ path: 'login/:id', canActivate: [AuthGuard], children: [] },
{ path: '', canActivateChild: [AuthGuard], children: [
{ path: '', redirectTo: '/courses', pathMatch: 'full' },
{ path: 'courses', component: CourseListComponent, pathMatch: 'full'},
{ path: 'courses/:courseId', component: CourseDetailComponent, pathMatch: 'full' },
{ path: 'courses/:courseId/unit/:unitId', component: CoursePlayComponent,
children: [
{ path: '', component: CourseListComponent },
{ path: 'lesson/:lessonId', component: CourseLessonComponent, data:{ type: 'lesson'} },
{ path: 'quiz/:quizId', component: CourseQuizComponent, data: {type: 'quiz'} }
]}
]},
{ path: '**', component: PageNotFoundComponent, pathMatch: 'full' }];
And auth.guard.ts
export class AuthGuard implements CanActivate , CanActivateChild {
constructor(private authUserService: AuthUserService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state:
RouterStateSnapshot): boolean |
Observable<boolean> | Promise<boolean> {
const id = +route.params.id;
if (id) {
this.router.navigate(["/courses"]);
return this.authUserService.login(id);
}
else if (this.authUserService.isLoggedIn())
return true;
else {
this.router.navigate(["/page_not_found"]);
return false;
}
}
canActivateChild(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean |
Observable<boolean> | Promise<boolean> {
return this.canActivate(route, state);
}
}
auth-user.service.ts
import { catchError, groupBy } from 'rxjs/operators';
import { UserService } from './user.service';
import { IUser } from './user';
@Injectable()
export class AuthUserService implements OnDestroy {
private user: IUser;
private errorMessage: string;
constructor(private userService: UserService) { }
login(id: number) {
return this.userService.getUser(id).pipe(
map((user) => {
this.user = user;
localStorage.setItem('user', JSON.stringify(this.user));
localStorage.setItem('token', 'JWT');
return true;
}),
catchError((error) => {
this.errorMessage = <any>error;
return of(false);
})
);
}
isLoggedIn() {
return !!localStorage.getItem('token');
}
ngOnDestroy() {
localStorage.removeItem('user');
localStorage.removeItem('token');
}
}
In my application there are many pages. Everybody need to login, but it only need to login one time. That is enough. My question is that if I am in the other page, how to retrieve the token to check if I already login?
What I have tried:
login(email:string, password:string) {
return this.httpClient.post<{access_token: string}>('http://www.your-server.com/auth/login', {email, password}).pipe(tap(res => {
localStorage.setItem('access_token', res.access_token);
}))
}