Ciro
Ciro

Reputation: 263

Create singleton class in typescript angular

I have a class with two method. I need to execute the first at the app bootstrap and the second few times during the application live.

My class:

import { Profile } from './Profile';

class Profilatura {
    public profile: Profile;

    /** @ngInject */
    first($http: angular.IHttpService): void{
      .......
      this.profile = ...;
      .......
    }

    public second(): Profile{
        return this.profile;
    }
}

In my app module:

import { ProfilaturaService } from './profilatura/ProfilaturaService';
angular.module('App')
    .run(function runBlock($http: angular.IHttpService) {
        Profilatura.first($http);
    })
    ....

Why I get Property 'first' doesn't exist on type typeof?????

Upvotes: 0

Views: 1427

Answers (1)

Shay Friedman
Shay Friedman

Reputation: 4868

Profilatura is a class object. You need to make first and second methods static. Beware - when you do that, you cannot use this inside the static methods anymore:

class Profilatura {
    public static profile: Profile;

    /** @ngInject */
    static first($http: angular.IHttpService): void{
      .......
      Profilatura.profile = ...;
      .......
    }

    static public second(): Profile{
        return this.profile;
    }
}

You can also make Profilatura a singleton class by doing something like this:

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

        public profile: Profile;

        /** @ngInject */
       first($http: angular.IHttpService): void{
          .......
          this.profile = ...;
          .......
        }

       public second(): Profile{
            return this.profile;
        }
    }

and then use it like:

Profilatura.getInstance().first(...)

Upvotes: 1

Related Questions