打字稿类可以注入到 JavaScript 控制器中吗?



我分别有一个TypeScript类和一个JavaScript控制器。TypeScript 类作为服务工作,而 JavaScript 控制器需要 Typescript 类才能使用它。我的问题:我该怎么做?

想法:我知道 AngularJS JavaScript 控制器不允许import语句,那么是否有可能通过依赖注入访问 TypeScript 类及其公共内容?

Javascript 控制器:

(function() {
  'use strict';
  angular
    .module('testModule')
    .controller('testModule.TestCtrl', TestCtrl);
  TestCtrl.$inject = [
    'testService' // <--- inject here? Note: not sure about this
  ];
  function TestCtrl(testService) {
    var ctrl = this;
    ctrl.$onInit = function() {
      // do stuff
    };
    ctrl.useTestService = function() {
      this.result = testService.makeItRain();
    };
  }
})();

打字稿服务

import { SomeStuffThatIsNeeded } from 'some/folder/structure';
export class TestService {
  static $name = 'TestService';
  static $inject = ['$window', '$location'];
  constructor(private $window: any, private $location: any) {
  }
  makeItRain() {
    this.doTheWaterDance();
  }
  private doTheWaterDance(): string {
    return 'get creative!'
  }
}

简短的回答,是的。您需要做的就是向 Angular 即服务注册该类。

import { TestService } from './TestService';
angular
    .module('testModule')
    .service('testService', TestService);

最新更新