Uland Nimblehoof
Uland Nimblehoof

Reputation: 1031

Correct way for importing abstract class to interceptor

I have issue with importing abstract class into http interceptor. Got error: 'method' is not a function. I have declared class in module:

@NgModule({
  declarations: [
    RootComponent
  ],
  imports: [
    BrowserModule,
    Ng2Webstorage,
    ApplicationRouterModule,
    HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService)
  ],
  exports: [],
  providers: [
    RootService,
    [**HttpCache**],
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true
    }
[...]

Also imported class to interceptor (actually I try to make caching interceptor):

import { HttpCache } from './interface/http-cache.interface';

@Injectable()
export class CachingInterceptor implements HttpInterceptor {

  constructor(private cache: HttpCache) {}
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (req.method !== 'GET') {
      console.warn('HTTP request different form GET');
      return next.handle(req);
    }

    console.warn('Caching Interceptor: ', this.cache);

    // First, check the cache to see if this request exists.
    const cachedResponse = this.cache.get(req);

Whole abstract class looks like:

export abstract class HttpCache {
  /**
   * Returns a cached response, if any, or null if not present.
   */
  abstract get(req: HttpRequest<any>): HttpResponse<any>|null;

  /**
   * Adds or updates the response in the cache.
   */
  abstract put(req: HttpRequest<any>, resp: HttpResponse<any>): void;
}

When I starting app, get error ERROR TypeError: this.cache.get is not a function.

Please for help this is connected to:

angular.io/guide/http#intercepting-all-requests-or-responses

Upvotes: 0

Views: 355

Answers (1)

Sandip Jaiswal
Sandip Jaiswal

Reputation: 3730

You are doing wrong. HttpCache is a abstract class and your need to implement methods of HttpCache class. Just Create a class and implement it. Write your logic in method put to cache request (data) you want and get those cached data from get.

Hope it will help

Upvotes: 2

Related Questions