0

I am in the process of preparing to migrate an AngularJS app to Angular. I am currently looking at converting the JS code to TS. I haven't had any issues with components and services but factories. I can't figure out how to convert factories to use TypeScript.

Here's an example:

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

I've tried this but doesn't work. I get 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;
          }
        }
      })
    })();

P.S. i do not have the ability to import/export classes yet.

1 Answer 1

1

Put the Fruit function inside the class constructor function and return it:

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

The DEMO on PLNKR

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.