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?