gpt4 book ai didi

javascript - 使用一个组件在多种状态下使用不同的服务方法

转载 作者:行者123 更新时间:2023-12-03 03:57:01 25 4
gpt4 key购买 nike

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

$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 状态,它将相应地使用 myService 中的 create() 方法,对于edit 以及我想要的其他状态。我如何设计我的组件以这种方式工作?

最佳答案

例如,您可以在其中一种情况下传递绑定(bind)(例如编辑):

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

关于javascript - 使用一个组件在多种状态下使用不同的服务方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44900115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com