Search code examples
angularangular-http-interceptors

When creating an interceptor in angular5, how do I let the request do it's normal thing?


import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpHeaders, HttpErrorResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import {NgbModal} from '@ng-bootstrap/ng-bootstrap';
import { ErrormodalComponent } from '../../features/errormodal/errormodal.component';
import { UploadComponent } from '../../features/upload/upload.component';


@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(private _ngbModal: NgbModal) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).do((event: HttpEvent<any>) => {
      // What to do here?
    }, (err: any) => {
      if(err instanceof HttpErrorResponse) {
        switch(err.status) {
          case 404:
            // API not found
            console.log('launch')
            this._ngbModal.open(UploadComponent, {size: 'lg', backdrop: 'static' })
            break
        }

        console.log('err', err)
      }
    })

  }
}

I get the error part, but what do I do where I have What to do here? in the event of a normal, non-error request / response?


Solution

  • I recommend to use catch operator instead of do :

    import { Injectable } from '@angular/core';
    import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpHeaders, HttpErrorResponse} from '@angular/common/http';
    import { Observable } from 'rxjs';
    import {NgbModal} from '@ng-bootstrap/ng-bootstrap';
    import { ErrormodalComponent } from '../../features/errormodal/errormodal.component';
    import { UploadComponent } from '../../features/upload/upload.component';
    
    
    @Injectable()
    export class ErrorInterceptor implements HttpInterceptor {
      constructor(private _ngbModal: NgbModal) {}
    
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).catch((err :  HttpErrorResponse) => {
            switch(err.status) {
              case 404:
                // API not found
                console.log('launch')
                this._ngbModal.open(UploadComponent, {size: 'lg', backdrop: 'static' })
                break
            }
    
            console.log('err', err);
            return Observable.throw(err);
          });
    
        }
    
      }
    

    you need to add ErrorInterceptor service to app module providers section like this

    providers :[
         { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
    ]