在typescript angular中创建singleton类



我有一个带有两个方法的类。我需要在应用程序引导程序中执行第一个,在应用程序运行期间执行第二个。

我的班级:

import { Profile } from './Profile';
class Profilatura {
    public profile: Profile;
    /** @ngInject */
    first($http: angular.IHttpService): void{
      .......
      this.profile = ...;
      .......
    }
    public second(): Profile{
        return this.profile;
    }
}

在我的应用程序模块中:

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

为什么我获取属性"first"不存在于类型为?????

Profiletura是一个类对象。您需要使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;
    }
}

您还可以通过以下操作使Profiletura成为一个单例类:

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(...)

最新更新