在typescript angular中创建singleton类

时间:2016-01-14 09:56:16

标签: angularjs typescript singleton

我有一个有两种方法的课。我需要在app bootstrap中执行第一次,在应用程序期间执行第二次。

我的课程:

import { Profile } from './Profile';

class Profilatura {
    public profile: Profile;

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

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

在我的app模块中:

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

为什么我首先获得物业'在类型typeof ?????

上不存在

1 个答案:

答案 0 :(得分:1)

Profilatura是一个类对象。您需要制作firstsecond方法static。注意 - 当你这样做时,你不能再在静态方法中使用this

class Profilatura {
    public static profile: Profile;

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

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

你也可以通过这样的方式使Profilatura成为单身人士课程:

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;
        }
    }

然后像:

一样使用它
Profilatura.getInstance().first(...)