Best practice for importing an abstract class into an interceptor

I encountered an issue while trying to import an abstract class into an HTTP interceptor. The error message I received was: 'method' is not a function. I have declared the class within the module as follows:

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

I also imported the class into the interceptor in an attempt to create a 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);

    // Checking the cache for the request.
    const cachedResponse = this.cache.get(req);

The structure of the abstract class is as follows:

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

Upon starting the app, I received the error

ERROR TypeError: this.cache.get is not a function
.

I would appreciate any help regarding this issue and it is related to:

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

Answer №1

It seems like you may be on the wrong track. HttpCache is actually an abstract class, which means you need to implement its methods in order to use it properly. Simply create a new class and start implementing the necessary methods. You can write your caching logic within the put method to store the data you need, and retrieve that cached data using the get method.

I hope this guidance proves helpful to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The mysterious button that reveals its text only when graced by the presence of a

The text on the button (Remove in this case) will only show up when the mouse is hovered over it. This issue is occurring in an angular project and despite trying to apply CSS for .btn, it does not get overridden. background-color: blue; Button's ...

Develop a query builder in TypeORM where the source table (FROM) is a join table

I am currently working on translating this SQL query into TypeORM using the QueryBuilder: SELECT user_places.user_id, place.mpath FROM public.user_root_places_place user_places INNER JOIN public.place place ON place.id = user_places.place_id The ...

When utilizing Ionic with Angular, it is difficult to access the hardware back button on mobile devices that have buttons located within the display/screen

When trying to access the hardware back button in my app, I encountered an issue where I couldn't produce an alert message to the user before the app closed. After posting a question on Stack Overflow (link of the question) and receiving help from the ...

Type narrowing is ineffective for discriminated unions in most cases

Consider the type definition provided below: type A = { a: string } | { a?: undefined; b: string } This essentially means that if you include a, it should be the only property provided. If you do not include or have a as undefined, then you also need to p ...

Is rc5 supported by angular-cli?

I recently downloaded and installed the latest Angular2 project with rc5 dependencies using "npm install" from angular2 quickstart on github. However, I noticed that angular-cli only supports rc4 dependencies in their package on GitHub. Is there a way to ...

Angular 2 and Bootstrap 4 combine to create a stunning side-by-side image display on your

I can't figure out how to display the images next to each otherhttps://i.sstatic.net/yMGgH.png <div class="row"> <div class="col"> <div *ngFor="let ir of imagesSource"> <div class="row"& ...

When launching the Angular SSR app, an uncaught ReferenceError occurs because the document is not defined

After successfully running "npm run dev:ssr" a problem arises when the rendered file shows an error. How can this issue be resolved? ERROR Error: Uncaught (in promise): ReferenceError: document is not defined ReferenceError: document is not defined a ...

Adding connected types to a list using Typescript

Question regarding Typescript fundamentals. In my code, I have a list that combines two types using the & operator. Here is how it's initialized: let objects: (Object & number)[] = []; I'm unsure how to add values to this list. I attem ...

Angular: implementing a service for conditional module imports

Currently, I have a service that is responsible for loading a list of modules: @Injectable() export class MyService { public allowedModules: any = this.modulesFilter(); constructor() { } public modulesFilter() { const testPef = true; co ...

What is a simple method to convert TypeScript to JavaScript?

Is it possible to eliminate TypeScript-specific keywords from a JavaScript file without using the tsc command, while ensuring that the file remains readable by humans and maintains JSX syntax? ...

Similar to TypeScript's `hasOwnProperty` counterpart

When working with TypeScript objects, is there a way to loop through a dictionary and set properties of another dictionary similar to how it is done in JavaScript? for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } } If ...

How can a material progress spinner be inserted into the Angular Ag-Grid overlayNoRowsTemplate?

I'm attempting to include a mat-progress-spinner within my agGrid when there are no rows to display. Here's an example that works: private overlayNoRowsTemplate = '<p>No rows to show.</p>'; However, when I attempt to add ...

If the numeral variable is used within an HTML function, a 'numeral is not defined' error may occur

Numeral.js is a key tool for me, utilized in both the viewmodels and occasionally in the HTML of my knockout components. <div data-bind="text: numeral(totalCurrent()).format('$0,0.00')"></div> While using webpack to bundle my HTML a ...

The module '@/assets/icons/pay/pay-success.png' cannot be located, along with its corresponding type declarations.ts

Recently, I encountered an issue while trying to import a png image in my Typescript code. Here is the snippet of code that caused the error: import paySuccessIcon from "@/assets/icons/pay/pay-success.png"; When I tried to import the image, Visual Studio ...

How to synchronize input field changes inside an ng-repeat loop and update the database using Angular

For a personal project involving a tournament, I have created a small Angular page. The matches are stored in an Oracle DB, from which I retrieve all the match details using PHP and store them in an array that includes the team names and goals scored. To ...

Steps to deploy an ASP.NET Angular application that has been published

I am working on an Angular application that is being managed by an ASP.NET application following a similar setup as described in this tutorial. During development, I usually use the command dotnet run from within the ASP.NET project directory to build both ...

Are there any solutions available for sending a POST request before closing a tab?

Currently, I am in need of a solution that allows me to unlock a deal when the tab is closed. The challenge lies in the fact that the lock status is stored in my database, and I must make a POST request upon tab closure to change the status of the deal to ...

"Embrace the powerful combination of WinJS, Angular, and TypeScript for

Currently, I am attempting to integrate winjs with Angular and TypeScript. The Angular-Winjs wrapper functions well, except when additional JavaScript is required for the Dom-Elements. In my scenario, I am trying to implement the split-view item. Although ...

Tips for incorporating a fresh attribute into a class through a class decorator

Looking to add a new property to a class using a class decorator? Here's an example: @MyClassDecorator class MyClass { myFirstName: string; myLastName: string; } // Need to achieve something like this: function MyClassDecorator (target: any ...

Tips for successfully transferring a JsonifyObject<T> from Remix's useLoaderData<typeof loader> to a function

Encountering a TypeScript error while trying to import JsonifyObject in the Remix 2.9.2 route code below... Argument of type 'JsonifyObject<IdAndDate>' is not assignable to parameter of type 'IdAndDate'. Struggling to figure ou ...