does http interceptor create for each request that is made?

Viewed 596

customInterceptor.js

counter = 0;

constructor() {
 console.log('interceptor : '+this.counter);
}

log

for login request: example.com/users

interceptor : 0
interceptor : 1 
interceptor : 2
interceptor : 3

logout and in again: example.com/users

interceptor : 10
interceptor : 11 
interceptor : 12
interceptor : 13

Tried to find out if i have created multiple instances of the interceptor servics, i called this from

app.module.ts

providers: [{
 provide: HTTP_INTERCEPTORS,
 useClass: customInterceptor,
 multi: true,
}],

http.service.ts

counter = 0;
req_counter = 0;

constructor(private injector: Injector) {
 console.debug(this.counter++, injector.get(HTTP_INTERCEPTORS);
}

get(url: string, options){
console.debug(req_counter++.concat(' : ', url);
 ...
}
1 Answers

In general, no. What you're seeing is probably because of the way dependency injection works. It doesn't have much to do with the fact that they are interceptors -- it would happen with every service.

Interceptors are services which you need to provide. If you provide them multiple times, multiple instances will be created when they need to be used.

Make sure that you are doing the following only in your main NgModule (usually named AppModule):

    providers: [
      {
        provide: HTTP_INTERCEPTORS,
        useClass: MyInterceptor,
        multi: true
      },
    ]

If you do it multiple times across different modules for the same interceptor (MyInterceptor), you'll get multipe instances (the construtor will be called many times, as you describe).

Related