将抽象类导入拦截器的正确方法

时间:2018-01-09 11:15:36

标签: angular typescript angular5

我有将抽象类导入http拦截器的问题。得到错误:'method'不是函数。我在模块中声明了类:

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

还导入拦截器类(实际上我尝试制作缓存拦截器):

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);

整个抽象类看起来像:

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;
}

当我启动应用时,会收到错误ERROR TypeError: this.cache.get is not a function

请联系我们:

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

1 个答案:

答案 0 :(得分:2)

你做错了。 HttpCache是​​一个抽象类,需要实现HttpCache类的方法。只需创建一个类并实现它。将您的逻辑写入您想要的缓存请求(数据)的方法中,并从get获取缓存数据。

希望它会有所帮助