2

I am working on an application in which I am calling a webservice and get a response. I am using that response in 2 different modules. In first module I am using as it is and in second module I am doing some formatting and using it.

I created a service for getting data as follows

angular.module('myApp').factory('getData',function($http, $q, restURLS) {

var getData= {};

getData.getTree = function () {
    var deferred = $q.defer();
    $http.get(restURLS.getTree).
        success(function (data) {
            deferred.resolve(data);
        }).error(deferred.reject);
        return deferred.promise;
    };
    return getData;
});

for Serving response I created another factory as follows

angular.module('myApp').factory('tree', function($http, $q, restURLS, getData, messages) {

  var tree= {};

  tree.hierarchy = {};
  tree.formattedHierarchy = {};

  function formatHierarchy(data) {
      //some formatting on data.
      tree.formattedHierarchy = data;
  }

  function callTree() {
      getData.getTree()
        .then(function (data) {
            tree.hierarchy = angular.copy(data);
            formatHierarchy(data);
        }).catch(function () {
            //error
        });
  }

  callTree();

   return tree;
});

I want to call webservice only once. if data is loaded then factory('tree') should send the data to controller. Otherwise factory('tree') should call webservice and load data.

1 Answer 1

1

you need something to know if you got your tree or not... try this:

(UPDATED)

var myApp = angular.module('myApp', ['ngMockE2E'])
// FAKE HTTP CALL JUST FOR EMULATE
    .run(function ($httpBackend) {

    var tree = [{
        node1: 'abcde'
    }, {
        node2: 'fghi'
    }];

    $httpBackend.whenGET('/tree').respond(function (method, url, data) {
        return [200, tree, {}];
    });
})
// YOUR HTTP SERVICE
    .factory('getData', function ($http, $q) {

    return {

        getTree: function () {
            var deferred = $q.defer();
            $http.get("/tree").
            success(function (data) {
                deferred.resolve(data);
            }).error(deferred.reject);
            return deferred.promise;
        }
    }
})
    .factory('TreeFactory', function ($http, $q, getData) {

    var tree = {};
    var updated = false;

    tree.hierarchy = {};
    tree.formattedHierarchy = {};

    function formatHierarchy(data) {
        //some formatting on data.
        tree.formattedHierarchy = data;
    }

    return {
        callTree: function() {
            if(!updated){
                console.log("making http call");
                return getData.getTree().then(function (data) {

                    tree.hierarchy = angular.copy(data);
                    formatHierarchy(data);
                    updated = true;
                    return tree;
                }).
                catch (function () {
                    //error
                });
            }else{
                console.log("tree already loaded");
                var deferred = $q.defer();
                deferred.resolve(tree);
                return deferred.promise;
            }

        }
    };


}).controller("MyCtrl", ['$scope', 'TreeFactory', function ($scope, TreeFactory) {

    $scope.updateTree = function(){
        TreeFactory.callTree().then(function(data){
            $scope.tree = data;
        });
    };
}]);

HTML

<div ng-app="myApp" ng-controller="MyCtrl" ng-init="updateTree()">tree: {{tree}} <br><button ng-click="updateTree()">UPDATE TREE</button></div>

CHECK THE FIDDLE

Sign up to request clarification or add additional context in comments.

4 Comments

somewhat right? but I am using "tree.hierarchy" in other modules. There I need to check whether it is loaded or not. if not then wait for it and den return promise and proceed.
is it like promise chaining you used ?
yes there is only 2 chain in there one for catch the data and one to set tree and update.
Thanks. I used same now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.