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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.