When using canActivate in history.guard, how can I verify if the user is logged in or not? The console always returns false as a value. Do I need to create a new function in auth.service or make edits directly in history.guard? Is there an alternative method to using subscribe?
auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs/Subject';
import { ApiService, VERSION, ENDPOINT } from '../api/api.service';
import { Observable, BehaviorSubject } from 'rxjs';
@Injectable()
export class AuthService {
logger = new BehaviorSubject<Object>(false);
referralRoute: string;
constructor(
private router: Router,
private api: ApiService
) {
}
// Other methods are omitted for brevity
}
history.guard.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../../core/service/auth/auth.service';
@Injectable({ providedIn: 'root' })
export class HistoryGuard implements CanActivate {
checkUserLogin: boolean;
constructor(
private router: Router,
private auth: AuthService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const checkUserLogin = this.auth.subscribeLogger().subscribe(
(data: any) => {
this.checkUserLogin = data;
}
);
if (!this.checkUserLogin) {
return this.router.navigate(['mypage']);
}
else {
return this.checkUserLogin;
}
}
}
history.module.ts
import { NgModule } from '@angular/core';
import { HistoryComponent } from './history.component';
import { HistoryItemComponent } from './history-item/history-item.component';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';
import { HistoryGuard } from './history.guard';
const routes: Routes = [
{
path: '',
component: HistoryComponent,
canActivate: [HistoryGuard]
},
{
path: ':id',
component: HistoryItemComponent,
canActivate: [HistoryGuard]
}
];
@NgModule({
imports: [
CommonModule,
RouterModule.forChild(routes)
],
declarations: [HistoryComponent, HistoryItemComponent]
})
export class HistoryModule { }