2017-07-04 3 views
0

実行する機能が非常に似ているため、異なる状態で再利用できるコンポーネントを作成したいと考えています。問題は、レンダリングされる状態に応じて、私のサービスとは異なるメソッドを使用することになっていることです。異なるサービスメソッドを持つ複数の状態で1つのコンポーネントを使用する

$stateProvider 
    .state('create', { 
     url: 'create', 
     component: 'myComponent', 
     resolve: { 
      data: function (myService) { 
       return myService.getData(); 
      } 
     } 
    }) 
    .state('edit', { 
     url: 'edit', 
     component: 'myComponent', 
     // another resolve 
    }) 
    // and so on 

をそして、私は次の方法でサービスを持っている:私のコンポーネントが描画されるかのようにするため

let myComponent = { 
    //bindings: {}, 
    controller: function() {}; 
    template: myTemplate 
} 

class myService { 
    // constructor($http) { this._$http = $http; } 
    create(smth) { 
     return this._$http.post(`${apiUrl}/smth`, smth).then(res => res.data); 
    } 

    edit(smth) { 
     return this._$http 
      .put(`${apiUrl}/smth/${smth.id}`, smth) 
      .then(res => res.data); 
    } 
} 

そして、私のコンポーネントを、私はこれらの状態に持って考えるとcreate州では、それに対応してmyServicecreate()メソッドを使用し、editとこれと同じものを使用します。そのような方法で私のコンポーネントを設計するにはどうすればいいですか?

答えて

1

たとえば、あなたが(編集など)のいずれかの場合に結合渡すことができます。

bindings: { isEditState: "<?"} 

サービス:コンポーネントで次に

class myService { 
// constructor($http) { this._$http = $http; } 
    makeRequest(smth, method) { 
    return this._$http[method](smth).then(res => res.data); // because they are pretty similar in your example 
    } 
} 

:最後に

makeReuest(smth) { 
    const reqMethod = isEditState ? "put" : "post"; 
    this.myService.makeRequest(smth, method); 
    // ... 
} 

、経路ではcomponentの代わりにtemplateを渡すことができます:

$stateProvider 
.state('create', { 
    url: 'create', 
    template: '<my-component></my-component>', 
    resolve: { 
     data: function (myService) { 
      return myService.getData(); 
     } 
    } 
}) 
.state('edit', { 
    url: 'edit', 
    template: '<my-component is-edit-state="true"></my-component>', 
    // another resolve 
}); 
+0

とはどのように呼びますか? – AlexNikolaev94

+0

申し訳ありませんが、私は私の 'put'メソッドと' post'メソッドにURLを提供しませんでした。更新された質問を参照 – AlexNikolaev94

+0

ルートで回答が更新されました。これがアイディアです。最終的な実装はあなた次第です。 –

関連する問題