javascriptangularjspolymerpolymer-1.0

http calls in polymer component as compared to angularjs services


I have one service which is being used by different webcomponents in my application. So i am thinking to create a webcomponent which will have my service and can be imported in my webcomponents wherever needed just as is done in angularjs.

In Angular

app.service('myService', function () {
    this.hello = function () {
        return "Hello World";
    };
    this.getData= function() {
      return $http({
        method: 'JSON', 
        url: 'SomeURL'
      });
}

In Polymer

<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>

Can anybody tell me what is the best way to achieve the same in Polymer.

Any help will be highly appreciated !!


Solution

  • One of the way which I found to implement service (Polymer 2 docs) is :

    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>
    

    Hope it also helps you!!