Angular services without Angular?

Angular ServicesĀ šŸ‘

  1. ā€‹narrow specific functions
  2. straight forward to understand
  3. singleton pattern

Same concept without Angular?

Maybe with Typescript?

Implementation of a singleton service with Typescript

export class SingletonService { private static instance: SingletonService; private constructor() { } static getInstance() { if (!SingletonService.instance) { SingletonService.instance = new SingletonService(); } return SingletonService.instance; } }

Wrong usage of our singleton service with Typescript

const myService: SingletonService = new SingletonService(); // TS2673: Constructor of class ā€˜SingletonServiceā€™ is private and only accessible within the class declaration.

Proper usage of our singleton service with Typescript

const myService: SingletonService = SingletonService.getInstance();

Examples

Author

David Dal Busco

Freelancer by day | Creator of DeckDeckGo by night
Twitter Dev GitHub Web

Read the full article on:

DEV or Medium