将AngularJS工厂迁移到TypeScript

时间:2019-05-02 00:25:01

标签: angularjs typescript factory angularjs-factory

我正在准备将AngularJS应用迁移到Angular。我目前正在寻找将JS代码转换为TS的方法。除了工厂,我对组件和服务没有任何问题。我不知道如何将工厂转换为使用TypeScript。

这是一个例子:

(function() {
    'use strict';

    angular.module('MyApp')
      .factory('Fruit', Fruit);

    /** @ngInject */
    function Fruit() {

      var Fruit = function(dto) {
        // dto properties
        this.id = "";
        this.name = "";
        this.type = "Orange";
        this.color = "#000000";

        //--------------
        // Create from API response DTO
        if (dto) {
          this.id = dto.id;
          this.name = dto.data.name;
          this.type = dto.data.type;
          this.color = dto.data.color;
        }
      };

      return Fruit;
    }
})();

我已经尝试过了,但是没有用。我得到dto->找不到dtoProvider。

(function() {
    'use strict';

    angular.module('MyApp')
      .factory('Fruit', class Fruit {

        // dto properties
        public id = "";
        public name = "";
        public type = "Orange";
        public color = "#000000";
        constructor (private dto: any) {
          // Create from API response DTO
          if (dto) {
            this.id = dto.id;
            this.name = dto.data.name;
            this.type = dto.data.type;
            this.color = dto.data.color;
          }
        }
      })
    })();

P.S。我还没有导入/导出课程的能力。

1 个答案:

答案 0 :(得分:1)

Fruit函数放入类构造函数中并返回:

class Fruit {
    constructor () {
        function Fruit(dto) {
            // dto properties
            this.id = "";
            this.name = "";
            this.type = "Orange";
            this.color = "#000000";
            //--------------
            // Create from API response DTO
            if (dto) {
                this.id = dto.id;
                this.name = dto.data.name;
                this.type = dto.data.type;
                this.color = dto.data.color;
            };
        }
        return Fruit;
    }
}

angular.module("myApp",[])
.factory("Fruit", Fruit);
.run(function(Fruit) {
  var x = new Fruit();
  console.log(x);
})

DEMO on PLNKR