使用具有不同服务方法的多个状态中的一个组件

时间:2017-07-04 07:54:46

标签: javascript angularjs web-component

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

$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 个答案:

答案 0 :(得分: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
});
相关问题