I am trying to implement HttpRequest caching using HttpInterceptor as per angular 4.3 documentation. But I get an error message. Here is my code:
caching.interceptor.ts
import { HttpRequest, HttpResponse, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/do'; import 'rxjs/add/observable/of'; abstract class HttpCache { abstract get(req: HttpRequest<any>): HttpResponse<any>|null; abstract put(req: HttpRequest<any>, resp: HttpResponse<any>): void; } @Injectable() export class CachingInterceptor implements HttpInterceptor { constructor(private cache: HttpCache) {} intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>> { if(req.method !== 'GET'){ return next.handle(req); } const cachedResponse = this.cache.get(req); if(cachedResponse){ return Observable.of(cachedResponse); } return next.handle(req).do(event => { if(event instanceof HttpResponse){ this.cache.put(req, event); } }) } }
Here, the CachingInterceptor works as an interceptor for an HTTP request / response. And I created a module a that looks like this:
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component/app.component'; import { HomePage } from './pages/home.page/home.page'; import { ProductsPage } from './pages/products.page/products.page'; import { AboutUsPage } from './pages/about-us.page/about-us.page'; import { UsersPage } from './pages/users.page/users.page'; import { DemoPage } from './pages/demo.page/demo.page'; import { appRouter } from './app.router/app.router'; import { CachingInterceptor } from './caching.interceptor/caching.interceptor'; import { AppService } from './app.service/app.service'; @NgModule({ imports: [ BrowserModule, HttpClientModule, appRouter ], declarations: [ AppComponent, HomePage, ProductsPage, DemoPage, AboutUsPage, UsersPage ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: CachingInterceptor, multi: true }, AppService ], bootstrap: [ AppComponent ] }) export class AppModule {}
The token is also provided in the providers of the [] module. This is consistent with the angular 4.3 documentation. But still I get an error, for example:
Error
ERROR Error: Uncaught (in promise): Error: No provider for HttpCache! Error: No provider for HttpCache! at injectionError (reflective_errors.ts:71)
I have 2 questions:
HttpCache is an abstract class, why is it introduced as a service?- Despite the fact that I implement it in accordance with the official documentation, why am I getting this error?
source share