Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to make a persistent login and everything works fine except if I am reload the page from the dashboard which is a page protected of AuthGuard I get redirected to login page but still I am logged in and also navbar works properly.Any suggestions would help me out a lot.

export class AuthGuard implements CanActivate {

    constructor(private auth: AuthService, private router: Router) {

    }

    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return this.auth.getLoggedIn
            .pipe(
                map((res: boolean) => {
                    console.log(res);  // this one returns false when I reload page    
                    if (!res) {
                        this.router.navigate(['login']);
                        return false;
                    }
                    return true;
                })
            );
    }
}

Below is my auth service

export class AuthService {

    private loggedIn: BehaviorSubject<boolean>;

    constructor(private http: HttpClient) {

        this.loggedIn = new BehaviorSubject<boolean>(false);
    }

    setLoggedIn(value: boolean) {
        this.loggedIn.next(value);
    }

    get getLoggedIn() {
        this.updatelogin().subscribe(res => {
            this.loggedIn.next(res);

        })
        return this.loggedIn.asObservable();
    }

    updatelogin() {
        return this.http.get<boolean>('/api/islogged'); // API server returns a boolean by calling req.isAuthenticated()-passport
    }
}

I deleted unnecessary code but if you need anything more let me know and I will edit my post.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
156 views
Welcome To Ask or Share your Answers For Others

1 Answer

Simply using a Subject instead of a BehaviorSubject should resolve the issue :

You start by creating a BehaviorSubject with a false value

this.loggedIn = new BehaviorSubject<boolean>(false);

Then you make an HTTP call to emit an new value

this.updatelogin().subscribe(res =>{
   this.loggedIn.next(res);
 })

But you don't wait for this call to end to return a value

return this.loggedIn.asObservable();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...