我有一个服务,我的应用程序中的不同webcomponents正在使用它。所以我想创建一个web组件,它将拥有我的服务,并且可以在我需要的web组件中导入,就像在angularjs中一样。
以角度
app.service('myService', function () {
this.hello = function () {
return "Hello World";
};
this.getData= function() {
return $http({
method: 'JSON',
url: 'SomeURL'
});
}
聚合物
<dom-module id="my-service">
<script>
var myService= new Object();
myService.hello = function () {
return "Hello World";
};
myService.getData= function() {
//How to convert this part in polymer context or we need to use <iron-ajax> , if yes then how?
});
}
</script>
有人能告诉我在聚合物中实现相同目标的最佳途径是什么。
任何帮助都将受到高度赞赏!!
答案 0 :(得分:0)
我发现实现服务(Polymer 2 docs)的一种方式是:
Axios:Axios docs
<script>
class MyService extends Polymer.Element {
static get is() { return 'my-service; }
static get properties() { url: 'my/service-url' }
getEndpoint(id) {
axios.get(this.url, {
params: {
ID: id
}
})
.then(function (response) {
console.log(response);
})
}
postEndpoint(params) {
//Use axios to post data from backend
}
}
customElements.define(MyService.is, MyService);
</script>
希望它对您也有帮助!