【问题标题】:Angular 1 and TypeScript: Dependencies Mixed with Properties in Class ConstructorAngular 1 和 TypeScript:依赖项与类构造函数中的属性混合
【发布时间】:2016-07-08 05:47:30
【问题描述】:

我有一个这样的 TypeScript 类:

  • 它不是 Angular 模块
  • 假设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);

【问题讨论】:

    标签: angularjs dependency-injection typescript


    【解决方案1】:

    您可以创建一个 factory 来注入 $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');
    });
    

    【讨论】:

    • 谢谢!如果我这样使用它,我会遇到错误angular.js:4442 Uncaught TypeError: PersonFactory is not a function。知道如何解决吗?
    • @Akarienta 工厂定义中有错字。现在应该修好了。
    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-16
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多