Singleton and Dependency Injection

Another handy pattern to use for frontend application is the singleton. The singleton ensures that only one instance of a given object exists in your program. Moreover, it provides a global point of access to the object.

Here's what it looks like in practice:

export class MySingleton{     private static instance:MySingleton = null; 
   //This constructor is private in order to prevent new creation  
   //of MySingleton objects    private constructor(){     }     public static getInstance():MySingleton{         if(MySingleton.instance == null){             MySingleton.instance = new MySingleton();         }         return MySingleton.instance;    } } let singleton:MySingleton = MySingleton.getInstance();

We have a class that has a private static instance:MySingleton ...

Get Expert Angular now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.