Error message: In Angular 2, when utilizing ng2-interceptor, the type 'ServerURLInterceptor' does not have a property called 'post'

I encountered an error while using angular2-interceptors in my Angular2 project. When attempting to call a POST/GET method, the following message appeared:

'Property 'post' does not exist on type 'ServerURLInterceptor'.'

I need guidance on where I might be making a mistake. My intention is to use interceptors to track every request, but whenever I try to make a request like GET or POST, it shows the error message saying that 'Property 'post' does not exist on type 'ServerURLInterceptor'.

Here is the code snippet:

The interceptorService.ts file:

import { Interceptor, InterceptedRequest, InterceptedResponse } from 'ng2-interceptors';
export class ServerURLInterceptor implements Interceptor {
    public interceptBefore(request: InterceptedRequest): InterceptedRequest {
         console.log(request);
        return request;
    }

    public interceptAfter(response: InterceptedResponse): InterceptedResponse { 
           console.log(response);
           return response;
    }
}

The app.module.ts file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MaterialModule } from '@angular/material';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { LoginComponent } from './components/login/login.component';
import { FormsModule } from '@angular/forms';
import { LoginService } from './helper/services/login.service';

import { InterceptorService } from 'ng2-interceptors';
import { ServerURLInterceptor } from './helper/interceptor/interceptorService';
import { XHRBackend, RequestOptions } from '@angular/http';
export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions, serverURLInterceptor:ServerURLInterceptor){
  let service = new InterceptorService(xhrBackend, requestOptions);
  service.addInterceptor(serverURLInterceptor);
  console.log("interceptor");
  return service;
}


@NgModule({
  imports: [ 
    MaterialModule.forRoot(),
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  declarations: [
    AppComponent,
    LoginComponent
  ],    
  providers: [
    LoginService,
    ServerURLInterceptor,
    {
      provide: InterceptorService,
      useFactory: interceptorFactory,
      deps: [XHRBackend, RequestOptions, ServerURLInterceptor]
    }
  ],                                         
  bootstrap: [ AppComponent ]
})
export class AppModule { }

The login.service.ts file:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http } from '@angular/http';
import { ServerURLInterceptor } from '../../helper/interceptor/interceptorService';        

@Injectable()
export class LoginService {
  constructor(private http:ServerURLInterceptor){}

  login(username:string,password:string) {
    console.log(username+" , "+password+" in LoginService");
    debugger;
    return this.http.post('http://localhost:4100/login',{
      email: username,
      password:password
    });
  }
}

Answer №1

To ensure that the InterceptorService is imported correctly, follow the code snippet provided below in your login.component.ts file:

import { InterceptorService     } from 'ng2-interceptors';

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 type '{}' does not contain the property specified AND 0 type arguments were expected, but 1 was provided

I have a function called useAuth() which manages the user in context. import { useContext } from "react"; import AuthContext from "../context/AuthContext_Provider" //AuthContext has been declared: const AuthContext = createContext({}); ...

Utilize Angular 5/Typescript to extract data from transformed JSON

After successfully retrieving an object using SOAP and HTTPClient from Angular5, I am currently facing challenges when attempting to extract specific values. The issue lies in the fact that I can only access all of them using: import {parseString ...

Error: inability to execute performanceMeasurement.startMeasurement due to its absence in the function definition

An error occurred when attempting to login using @azure/msal-react in Next 13. Upon checking the error log, it was found that the error originated from the core library @azure/msal-react. Even after trying with a login popup, the error persisted. In my co ...

What alternative approach can be used to substitute initEvent in typescript?

I am interested in manually triggering a MouseEvent in typescript, but I have discovered that the initEvent method is deprecated. var clickEvent =document.createEvent('MouseEvent'); clickEvent.initEvent('mouseup',true,true); https://i. ...

Prevent API requests with a toggle button in RxJS to start and stop calls

I have been diving into Rxjs and managed to put together a simple slideshow that updates the images every 5 seconds after clicking the start button. However, I am struggling to figure out how to pause/stop the API fetching process once the button is clicke ...

Component-driven form validation in Angular 2

I'm facing a challenge with implementing model-driven form validation in my custom input component. Specifically, I need to figure out how to pass ngControl to the component. In the plunkr demo provided at http://plnkr.co/edit/QTmxl8ij5Z6E3xKh45hI?p= ...

Filtering an array of objects in TypeScript based on the existence of a specific property

I'm attempting to filter objects based on whether or not they have a specific property. For example: objectArray = [{a: "", b: ""}, {a: ""}] objectArray.filter( obj => "b" in obj ).forEach(obj => console. ...

Updating Angular 9 values using a fixed object

I am dealing with a patch value here where I simply pass an object to it. this.formPesquisar.controls['daniloTeste'].patchValue(this.dadosVisualizar.daniloTeste); However, I would like to pass a static object instead, something like: this.formPe ...

"Applying UseQueryWithStore functions correctly, whereas useGetList does not yield the

I have a component that retrieves a list of items from the data provider in this way: const { data, total, loading, loaded, error, refetch } = useQueryWithStore({ type: 'getList', resource: 'client/account', payload: { ...

The array is showing as empty with a length of 0, despite the fact that the debug console displays items

Something unusual is happening with my code. Most answers I've seen online talk about waiting for data, but that's not the issue here; the JSON source is within the HTML itself. An array of items mysteriously has a length of zero, causing the fo ...

A new feature reminiscent of grace has been introduced in the most recent release of ChartJs 2.9.3

Incorporating ng2-charts into my angular project for chart generation has been quite useful. It relies on ChartJs2.9.3. Within the project, I have utilized a shared ChartOptions for various dynamically generated charts with varying values. However, the cha ...

Experiencing difficulties establishing a connection with my NodeJs server socket and TypeScript

I've been struggling to run the code from this post and I really need some help. The code can be found at: https://medium.com/@mogold/nodejs-socket-io-express-multiple-modules-13f9f7daed4c. I liked the code as it seems suitable for large projects, but ...

Tips for personalizing the Material UI autocomplete drop-down menu

I'm currently working with Material UI v5 beta1 and I've been attempting to customize the Autocomplete component. My goal is to change the Typography color on the options from black to white when an item is selected. However, I'm struggling ...

Encountering problem with React Typescript fetching data from Spring Data REST API: the error message "Property '_embedded' does not exist" is being displayed

I am currently working on a React application that utilizes Typescript to fetch data from a Spring Data REST API (JPA repositories). When I make a specific request like "GET http://localhost:8080/notifications/1" with an ID, my JSON response does not pose ...

Circular dependencies may arise when utilizing @UseGuards in a controller and encountering undefined dependencies

Recently, while working on my app with NestJS, I came across an issue related to the use of guards using @UseGuards(). In order to protect my controller, I created two guards as follows: JwtAuthGuard: import { AuthGuard } from '@nestjs/passport' ...

Adjusting the Port Setting in Nuxt 3

After trying the old solution without success, I decided to refer to the Nuxt 3 documentation for answers, only to find that it was not up to date. So, is there a way to change the Nuxt 3 port without modifying the dev script, similar to what @kissu did h ...

Showcasing a single JSON object in an Angular application

After receiving a Json object from an API, I attempted to display it in my component with no success. Below is the code snippet of my component: selector: 'app-links-page-detail', templateUrl: './links-page-detail.component.html', ...

Angular Validation Custom Control does not retrieve form values

In my form-validators.ts file, I encountered an issue where the code snippet below always returned undefined, causing the custom validation function matchPwdValidator() to consistently return false. By moving the logic to fetch confirmPwd inside the switch ...

Troubleshooting problem with GZIP in Angular 2 application deployment

I have developed an Angular 2 TypeScript application. I am using Firebase for hosting and Cloudflare for optimizing speed, caching, and security. When checking the browser header, it indicates: accept-encoding:gzip, deflate, sdch, br The app.js file has ...

Error encountered: NextJs could not find the specified module, which includes Typescript and SCSS

I am in the process of migrating a Next.js application from .js to .ts and incorporating ScSS. The first error I encounter is during 'npm run dev'. However, when I try 'npm run build', different issues arise that do not seem related to ...