The observable below highlights the authentication process:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CookieService } from 'ngx-cookie-service';
import { Observable } from 'rxjs';
@Injectable()
export class AuthService {
readonly loginUrl = <login_url>;
readonly authStatusUrl = <auth_status_url>;
constructor(private http: HttpClient, private cookieService: CookieService) {}
loggingIn = false;
login(username: string, password: string) {
this.loggingIn = true;
const creds = {
username: username,
password: password
};
this.http
.post<any>(this.loginUrl, creds, {})
.subscribe(
data => this.onLoginSuccess(data),
error => this.onLoginFail(error));
}
handleAuth(): Observable<any> {
const token = this.cookieService.get('token');
const refresh = this.cookieService.get('refresh');
// should wait for loggingIn to be false
return this.http
.post<any>(this.authStatusUrl, { }, {
headers: {
token: token,
refresh: refresh
}
});
}
public onLoginSuccess(data) {
this.loggingIn = false;
this.cookieService.set('token', data.access_token);
this.cookieService.set('refresh', data.refresh_token);
}
onLoginFail(err) {
console.log('Failed to login');
this.loggingIn = false;
}
}
The function should only run if a local variable is set to false.
I have come across suggestions of using Promises and async function calls with the await operator to achieve this, however, I am struggling to find a solution that effectively polls for the variable value rather than just waiting for a specific amount of time before resolving.
The primary goal is to invoke handleAuth while ensuring that no ongoing login operation is in progress, by monitoring the local variable or another triggering event.