【问题标题】:Migrating an AngularJS factory to TypeScript将 AngularJS 工厂迁移到 TypeScript
【发布时间】:2019-05-02 00:25:00
【问题描述】:

我正在准备将 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 not found.

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

附:我还没有导入/导出类的能力。

【问题讨论】:

    标签: angularjs typescript factory angularjs-factory


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2014-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 2014-11-24
      相关资源
      最近更新 更多