Home > Mobile >  Interceptor create two instances of singleton service
Interceptor create two instances of singleton service

Time:09-22

I have LoginService which MUST be singleton - but angular create two instances and use them randomly - here is my code:

app.module.ts :

providers: [
        { provide: AbstractLoginService, useClass: LoginService },
        { provide: HTTP_INTERCEPTORS, useClass: HTTPDemoInterceptor, multi: true },
        ...
]

HTTPDemo.interceptor.ts :

@Injectable({ providedIn: 'root' })
export class HTTPDemoInterceptor implements HttpInterceptor {

    constructor(
        private AbstractLoginService: LoginService,
    ) { 
      console.log('CONSTRUCTOR HTTPDemoInterceptor');
    }

login.service.ts

@Injectable({ providedIn: 'root' })
export class LoginService implements AbstractLoginService {
    private timestamp = 0

    constructor(private timestamp = 0;) {
        this.timestamp =  new Date();
        console.trace('CONSTRUCTOR LoginService', this.timestamp);
    }

abstract-login.service.ts

@Injectable({ providedIn: 'root' })
export abstract class AbstractLoginService {
   // (no constructor) ...

When I run code I see in console

CONSTRUCTOR LoginService 1632224055035
CONSTRUCTOR LoginService 1632224055036
CONSTRUCTOR HTTPDemoInterceptor

Here are screenshots with stacktraces (first constructor call on left, second on right) - we see clearly that HTTPDemoInterceptor constructor is call only once, but LoginService is called twice. How to fix it?

enter image description here

CodePudding user response:

You are providing your service twice, once through the providedIn property in injectable decorator, the other is when you add it to the providers array in your module, that's why there are 2 different instances of the service, just use one approach to provide your service.

  • Related