2017-07-04 55 views
0

我想构建一个组件,我可以在不同状态下重新使用组件,因为它执行的功能非常相似。问题在于,根据呈现的状态,它应该使用来自我的服务的不同方法。考虑到我有以下状态:使用不同服务方法的多个状态中的一个组件

$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 

而且我有以下方法服务:

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

而且我的组件:

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

所以,如果我的组件呈现在create的状态下,它会使用create()方法从myService相应地,并且相同的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); 
    // ... 
} 

最后,在路线中,您可以通过template而不是component

$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

更新了路线答案。这是主意。最终的实施取决于你。 –

相关问题