HttpRequest
キャッシュを実装するには、HttpInterceptor
を角度4.3のドキュメントに従って使用しています。しかし、私はエラーが発生しています。ここに私のコードは次のとおりです。4.3のHttpInterceptorを使用してキャッシュできません
caching.interceptor.ts HTTPリクエスト/レスポンスのためのインターセプタとして
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);
}
})
}
}
ここCachingInterceptor
作品。そして私は、モジュールを作成したように見えた:
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 {}
トークンは、[]モジュールのプロバイダで提供されます。これは、角度4.3の文書によるものです。しかし、それでもまだ、私は取得していますエラーのように:それはサービスのように注入されている理由
HttpCache
が、その後、抽象クラスである:エラー
ERROR Error: Uncaught (in promise): Error: No provider for HttpCache! Error: No provider for HttpCache! at injectionError (reflective_errors.ts:71)
私は2つの質問がありますか?
- 公式のドキュメントに従って実装していますが、なぜそのエラーが発生しますか?
私はマルチリクエストバグを修正するために私の答えを更新しました。 –
ありがとう@WillShaver – Shree