DevStacker
DevStacker

Reputation: 735

Angular canActivate get updated variable from service

I have a post request from a service which returns if a user is logged in, and I want to set a authGuard to only show the admin panel when they are logged in. My post request is as follows:

public isLoggedIn: boolean = false;
checkSesh(data: object) {
    const options = {
      headers: new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8'),
      withCredentials: true
    }

    return this.http.post<any>(`${this.AUTH_SERVER}`, data, options).subscribe(
      (res) => {
        this.reload = res[0].reload;
        if (this.reload === 0) {
          this.isLoggedIn = true;
        }
      }
    );
  }

My authguard has the following:

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {    
    return this.service.isLoggedIn;
  }

But it returns false (it is getting the boolean value before the subscribe).

How could I update it after the post request has run and the value has updated?

Thanks

Upvotes: 0

Views: 260

Answers (1)

anjapopovic
anjapopovic

Reputation: 36

you need to return Observable as a result in canActivate function. So you can just map the result in checkSesh function, to return true/ false. So something like this:

checkSesh(data: object) {
    const options = {
        headers: new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8'),
        withCredentials: true
    }

    return this.http.post<any>(`${this.AUTH_SERVER}`, data, options)
        .pipe(
            map((res) => {
                this.reload = res[0].reload;
                if (this.reload === 0) {
                    this.isLoggedIn = true;
                    return true;
                }
                return false;
            })
        );
}

And then just in canActivate function you can do following:

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    return this.service.checkSesh();
}

Upvotes: 1

Related Questions