Home > Net >  Use Angular interceptor without next.handle
Use Angular interceptor without next.handle

Time:07-12

as i understood from angular interceptors documentation that next.handle() executes tasks after the HTTP request is done , so i tried using the intercept method without the next.handle() to run code before the execution of the HTTP request

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            if (!this.connectivityService.networkStatus.connected) {
                return throwError({message: 'error returned from interceptor'});
            }

    }

is it possible to use angular interceptor without next.handle() ?

CodePudding user response:

The solution to the clarified problem from your comments is as follows:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            if (!this.connectivityService.networkStatus.connected) {
                return throwError({message: 'error returned from interceptor'});
            }
            next.handle();

    }

You call next.handle() in all non-error scenarios so that the http request continues if there's no error, but is interrupted by the error condition.

Your interceptor is part of a pipeline, a chain made of multiple steps, and you let the process move to the next step with next.handle(). This means that you can place code before next.handle() that needs to happen before the HTTP request, and you can place code after next.handle() that needs to happen after the pipeline has completed. If you don't call next.handle, the pipeline is interrupted and doesn't happen. You return a throwError observable so that that is the end of the pipeline. It looks a bit like this in the non-error scenario:

A {
  B {
    C {
      http happens
    }
  }
}

And like this in the error scenario:

A {
  B {
    returns error value
  }
}

If B were your interceptor, and A and C some other parts of the pipeline.

  • Related