I'm trying to make intercept
function waits for Promise
to be resolved before each API
call to check user if still active or not , if he is active I'll perform his request other wise I'll return EMPTY;
(Prevent him from editing and logout) like this
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(
private userChecker: UserChecker
) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
// custom code for headers
let x = this.userChecker.getUserStatus(); // this function call API and will return a promise that resolve boolean true if he is still active and false if not
/* try 1
x.then((resolve) => {
if (!resolve) {
// logut
}else return next.handle(request);
});
*/
/*try 2
if(userChecker.shouldLogout){
// logout
}else return next.handle(request);
*/
//this is the normal state without any try of above
return next.handle(request);
}
At Try1 : will continue execution without returning anything either if it resolve true or false
At Try2 :
will continue before shouldLogout
modified in API subscription
How do I prevent intercept
from continue execution until I receive the flag from the API
to continue or logout
You should convert your promise to an Observable
instead with from
. Then use filter
to prevent the request from happening unless the shouldLogout
flag is set to false:
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return from(this.userChecker.getUserStatus()).pipe(
filter(() => !this.userChecker.shouldLogout),
mergeMap(() => next.handle(request))
);