如何处理TypeScript中的闭包(角度注入)?

时间:2016-04-22 01:16:34

标签: javascript angularjs typescript closures

我在JavaScript中有一个Angular工厂服务,我这样定义:

app.service('MyServiceFactory', ['$http', '$timeout', '$interval',
  function($http, $timeout, $interval) {

  function MyService() {
    // I can use all injected values here without additional efforts
  }

  this.Create = function() {
    return new MyService();
  }

}]);

现在我想将其转换为TypeScript:

module Services {

  export class MyServiceFactory {
    static $inject: string[] = ['$timeout', '$interval', '$http'];

    constructor(
      private timeout: angular.ITimeoutService,
      private interval: angular.IIntervalService,
      private http: angular.IHttpService) {
    }
    public create(): MyService { return new MyService(); };
  }

  export class MyService() {
    // I have a problem here. I need to redefine and
    // initialize all variables, injected into my factory class
  }

  angular.module('MyModule').service('MyServiceFactory', MyServiceFactory);
}

你明白我的意思吗? TypeScript不允许嵌套类,这可能解决了这个问题。此外,TypeScript解决方案看起来非常不酷。有更优雅的解决方案吗?

2 个答案:

答案 0 :(得分:0)

而不是:

export class MyService() {
    // I have a problem here. I need to redefine and
    // initialize all variables, injected into my factory class
  }

您可以将Create放在MyServiceFactory上,即:

module Services {

  export class MyServiceFactory {
    static $inject: string[] = ['$timeout', '$interval', '$http'];

    constructor(
      private timeout: angular.ITimeoutService,
      private interval: angular.IIntervalService,
      private http: angular.IHttpService) {
    }
    public create(){ 
      // Use the revealing module pattern 
      // And let the compiler infer the return type
      // e.g.
      var foo = 23;
      return {
         foo
      }
    };
  }

  angular.module('MyModule').service('MyServiceFactory', MyServiceFactory);
}

请注意,有效的JavaScript是有效的TypeScript(more

答案 1 :(得分:0)

您可以将注入的变量作为参数传递给其他类,例如:

export class MyServiceFactory {
  static $inject: string[] = ['$timeout', '$interval', '$http'];

  constructor(
    private timeout: angular.ITimeoutService,
    private interval: angular.IIntervalService,
    private http: angular.IHttpService) {

  }

  public create(): MyService {
    return new MyService(this.timeout, this.interval, this.http);
  }
}

export class MyService {
  constructor(
    private timeout: angular.ITimeoutService,
    private interval: angular.IIntervalService,
    private http: angular.IHttpService) {
    // no more problems here, you can play with the injected variables again
  }
}

angular.module('MyModule').service('MyServiceFactory', MyServiceFactory);