Angular 1 和 TypeScript:与类构造函数中的属性混合的依赖项



我有一个这样的TypeScript类:

  • 它不是角度模块
  • 假设personName是本示例中无法在视图/模板上使用的自定义筛选器

法典:

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

这可以像这样在控制器中使用:

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

是否可以重写Person类,以便在没有$filter的情况下启动?换句话说,我可以通过依赖注入将类Person类编写为 Angular 工厂,然后将该工厂注入控制器并创建实例吗?

我想要这样的东西:

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

您可以创建一个工厂,该工厂注入$filter服务并返回一个函数,该函数接受其余参数并返回 Person

它看起来像这样。

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

您将能够像这样使用它:

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

最新更新