JSFiddle - React, Tailwind, and code Playground

by ravimallya

JavaScript

.factory('menuItemsService', function($http) {
      var promise;
      var myService = {
          async: function() {
              if (!promise) { // $http returns a promise, which has a then function, which also returns a promise
              promise = $http.get(APIURI + 'User/GetAllMainCommodities').then(function (response) { // The then function here is an opportunity to modify the response
              localStorage.setItem("MainCommodityId", response.data[0].MainCommodityId);
              localStorage.setItem("MainCommodityName", response.data[0].MainCommodityName); // The return value gets picked up by the then in the controller. 
              return response.data; }); } // Return the promise to the controller 
              return promise; }
              }; 
              return myService; })
                $scope.data = []; // Call the async method and then do stuff with what is returned inside our own then function
                menuItemsService.async().then(function (d) { 
                $scope.data = d;
                });