Johan Aspeling
Johan Aspeling

Reputation: 817

Singleton service in Angular 7

I have the following service:

export abstract class ILoggingService {
    // abstract functions here
}

export class LoggingService implements ILoggingService {
    // service implementation
}

export class MockLoggingService implements ILoggingService {
    // service implementation
}

Which I provide in the required modules using:

@NgModule()
export class SomeModule {
    providers: [
        { provide: ILoggingService, useClass: LoggingService }
    ]
}

Normal usage:

@Component({  
    selector: 'test-component',
    template: ''
})
export class TestComponent {
    constructor(private readonly loggingService: ILoggingService) {
        // resolves to the correct instance (LoggingService), but not a singleton.
    }
}

I'm failing to create a singleton for this LoggingService. I have tried creating a LoggingServiceModule which uses the forRoot() strategy, which I couldn't get working.

I'm also not sure how to use the provideIn: 'root' implementation, as it needs to be provided using { provide: ILoggingService, useClass: LoggingService }?

How can I combine the implementation where I map an interface (abstract class) to a concrete type, and the singleton pattern?

Upvotes: 2

Views: 2990

Answers (1)

Siddharth Pal
Siddharth Pal

Reputation: 1458

@Injectable({providedIn: 'root', useClass: LoggingService})
export abstract class ILoggingService {
 // abstract functions here
}

Thanks to this article

Upvotes: 3

Related Questions