2016-03-21 17 views
0

と混合依存性:角度1と活字体:私はこのような活字体クラスを持つクラスのコンストラクタでのプロパティ

  • それは角度モジュール
  • ではありませんが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); 

はそれが$filterなしinitedすることができますしPersonクラスを書き換えることは可能ですか?言い換えると、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); 

答えて

1

あなたは$フィルタサービスを注入し、残りのパラメータを受け取り、返す関数を返す工場を行うことができます。

私はこのような何かをしたいのですが

このようになります。

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'); 
}); 
+0

ありがとうございました!私がそれを使用すると、私はエラー 'angular.js:4442 Uncaught TypeError:PersonFactoryは関数ではありません.'を持っています。どのようにそれを解決するための任意のアイデア? –

+0

@Akarienta工場定義でタイプミスがありました。今すぐ修正する必要があります。 – toskv

関連する問題