Knut Holm
Knut Holm

Reputation: 4162

Angular 1 and TypeScript: Dependencies Mixed with Properties in Class Constructor

I have a TypeScript class like this:

Code:

export class Person {
   private $filter;
   private name: string;
   private sureName: string;

   constructor($filter: ng.IFilterService, name: string, sureName: string) {
      this.$filter = $filter;
      this.name = name;
      this.sureName = sureName;
   }

   public getName(): string {
      return this.$filter('personName')(this.name, this.sureName);  
   }
}

This can be used in controller like this:

export class PeopleController {
   private $filter: ng.IFilterService;
   private person1 = new Person(this.$filter, 'Joe', 'Smith');
   private person2 = new Person(this.$filter, 'John', 'Doe');
   // ...
   // private person100 = new Person(this.$filter, ...)

   constructor($filter: ng.IFilterService) {
      this.$filter = $filter;
   }
}

angular.module('myApp').controller('PeopleController', PeopleController);

Is it possible to rewrite Person class to can be inited without the $filter? In other words, can I write Person class as Angular factory with dependency injection, then inject this factory into controller and make instances?

I'd like to have something like this:

export class PeopleController {
   private PersonFactory: Person;
   private person1 = new PersonFactory('Joe', 'Smith');
   private person2 = new PersonFactory('John', 'Doe');
   // ...
   // private person100 = new Person(...)

   constructor(PersonFactory: Person) {
      this.PersonFactory = PersonFactory;
   }
}

angular.module('myApp').factory('PeopleFactory', People);
angular.module('myApp').controller('PeopleController', PeopleController);

Upvotes: 0

Views: 155

Answers (1)

toskv
toskv

Reputation: 31600

You can make a factory that injects the $filter service and returns a function that takes the rest of the parameters and returns a Person.

It would look something like this.

interface PersonFactory {
    (name: string, surname: string): Person
}

angular.module('mymodule').factory('PersonFactory', function($filter: ng.IFilterService): PersonFactory {
    return function(name: string, surname: string): Person {
        return new Person($filter, name, surname);
    }
});

You will be able to use it like this:

angular.module('myModule').controller('SomeCtrl', function(PersonFactory: PersonFactory) {
    let p = PersonFactory('John', 'Smith');
});

Upvotes: 1

Related Questions