2016-04-08 13 views
1

私がしたいのは、いくつかの引数(new book( 'someTitle'))を使ってインスタンス化できるES6の角をなすモデル(Bookなど)を作成することです。私はそれが次の作業持っている(私たちは、このような$ HTTPなど、何かを注入する必要があるとし):ES6でAngularでモデルを作成する

function foo($http) { 
    return class Book { 
     constructor(title) { 
      this.title = title; 
     } 
     fetch() { 
      return $http.get('api/book/' + this.title); 
     //... 
     } 
    }; 
} 
angular.module('app') 
    .service('Book', ['$http', function($http) { 
     return foo($http); 
    }]; 

問題は、これは物事のきれいな方法のようには思えないです。また、どのような問題が出てくるのかよく分かりません。誰もが同じことを達成するためのよりよい方法を提案できますか?

+0

なぜあなたは 'foo'機能を持っていますか?あなたは工場でクラスを返すことができます。それはそれをより明確にするでしょう。これがangular1の仕組みです。ところで、私はこの質問がes6にどのように関係しているのか本当に見ません。 es5クラスを使用する場合も同じです。 –

答えて

1

私はこれをtypescriptで行っていますが、関数内でクラスをラップする代わりに、クラスのファクトリを返す静的ファクトリ関数があります。これは少しきれいに見えるかもしれません。このようになります...これは本当にきれいに見えるために取得する

class Book { 
    constructor(public $http) {} 

    set(title) { 
     this.title = title; 
    } 

    fetch() { 
     return this.$http.get('api/book/' + this.title); 
    } 

    static factory() { 
     let service = ($http) => { 
     return new Book($http); 
     } 

     service.inject = ['$http']; 
     return service; 
    } 
} 

angular.module('app') 
     .service('Book', Book.factory()); 

もう一つの方法は、彼らがAngular2にやったのは、現在の活字体で作業しているES2016/2017デコレータ、です。とにかく、ただのアイデア!

+1

お返事ありがとうございます。モデルをインスタンス化してタイトルを付ける(たとえば、新しいBook( 'someTitle'))が、あなたのアプローチではBookは$ httpで構築され、set(title)を呼び出してタイトルを設定する必要があります。 – brickingup

0

ファクトリが定義されたクラスを作成することができます。静的メソッドを作成すると、クラス名を介してメソッドにアクセスできます。

class refreshFactory { 

    constructor($scope) { 
     'ngInject'; 
     this.callbacks = {}; 
     this.$scope = $scope; 
    } 

    testmethod() { 
     alert(); 
    } 


    static refreshFunctions ($scope) { 
     'ngInject'; 
     return new refreshFactory($scope); 
    } 
} 

export default refreshFactory; 

// Create the module where our functionality can attach to 
let CommonFactory = angular.module('common.factories', []); 

import refreshFactory from './refresh.factory'; 
CommonFactory.factory('refreshFactory', refreshFactory.refreshFunctions); 
関連する問題