Show modal dialog from HttpInterceptor

Issue

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {

    //show a modal dialog to hold the request until user respond/close the dialog
    if(ShowModalDialog()) 
       return next.handle(req);
     else
       route to login
  }
}

I have tried to show a angular material dialog but it does not block the request and continue execute to next line.

How to show a modal dialog from intercepter on finding the request is errored out, show user some options and resume execution after dialog is closed.

Is it possible to stop/hold a request with such dialog?

Solution

You can do this with an angular material dialog:

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  constructor(private dialog: MatDialog, private router: Router) {}
  
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if(ShowModalDialog()) {
      return this.dialog.open(DialogModalComponent).afterClosed().pipe(
        concatMap(() => next.handle(req))
      );
    } else {
      return next.handle(req);
    }
  }
}

Answered By – Poul Kruijt

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.