Reputation: 21
I'm trying to use a route guard to check if a user I logged in before accessing a route. for that i have a replaySubject contains true if a user is logged in. when i call my method for checking whether the user is logged in it's value is true, but when calling the same method inside a canActivate method it's value is empty so it does not return anything.
the canActivate
method:
//inside AuthService
canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> {
return this.isLoggedIn();
}
the isLoggedIn
method:
//inside AuthService
isLoggedIn() {
return this.loggedIn
.first()
.do(user => {
console.log(user);
})
}
the loggedIn
subject:
//inside AuthService
loggedIn: Subject<boolean> = new ReplaySubject<boolean>(1);
the link:
<a (click)="checkLogin()" [routerLink]="['/table']">some text</a>
checkLogin
method:
checkLogin() {
this.auth
.isLoggedIn()
.toPromise()
.then(data => {
// this returns true
console.log("login status is", data);
});
}
the routing module:
const appRoutes: Routes = [
{ path: "home", component: HomeComponent },
{ path: "table", component: TableComponent, canActivate: [AuthService] },
{ path: "", redirectTo: "/home", pathMatch: "full" }
];
angular version: 5.2.8, angular router version: 5.2.8
Upvotes: 1
Views: 561
Reputation: 21
thank you Pierre for pointing me in the right direction
turns out i provided my auth service in both my app component and my app module which in turn caused me to have two instences of my auth service in the app, one for my components and one for my modules.
i just deleted the service from the app component and it worked
Upvotes: 0