Search code examples
angularangular-httprxjs6

HttpInterceptor with observable 'intercept' in type 'AuthenticationInterceptor' is not > same property in base type 'HttpInterceptor'


I don't understand what's wrong with this code can you help me, please ?

import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';

import { Observable } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';

import { AuthenticationSharedStorage } from '../storages/authentication.storage';
import { AuthenticationToken } from '../../models/authentication.model';

@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {

  constructor(private storage: AuthenticationSharedStorage) {}
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    this.storage.getData()
    .pipe(
      switchMap((data:AuthenticationToken )=> {
      if(data){
        const authToken = data.token;
        const authReq = req.clone({ setHeaders: { Authorization: authToken } });
        return next.handle(authReq);
      }
      return next.handle(req);
      })
    );
  }
}

The complete error is:

Property 'intercept' in type 'AuthenticationInterceptor' is not assignable to the same property in base type 'HttpInterceptor'. Type '(req: HttpRequest, next: HttpHandler) => void' is not assignable to type '(req: HttpRequest, next: HttpHandler) => Observable>'. Type 'void' is not assignable to type 'Observable>'. 16:3


Solution

  • You need to return an Observable<HttpEvent<any>> from intercept - currently nothing is returned. Assuming this.storage.getData() returns one (likely true since it has pipe()) then just put a return before it.

    intercept(req: HttpRequest<any>, next: HttpHandler) {
      return this.storage.getData()
      //...
    }