1

I need translate value factory. this factory receive translateData from server. and angular controller call convertValue function. but $http is async method so controller get undefined value. because http response not yet received.

I wonder that I can factory initialize complete(= download data from server) and create controller sequentially.

angular.module("app")
.factory("service", function ($http) {
    var allDataMap = {};

    $http({
        method: 'GET',
        url: '/data'
    }).then(function (response) {
        angular.forEach(response.data.datas, function (value) {
            allDataMap[value.key] = value.value;
        });
    });


    return {
        convertValue: function (key) {
            return key + '(' + allDataMap[key] + ')';
        },  
    };
});
2
  • We do not write business logic in factory. That just acts as a data access layer. You should be calling api and return that promise object to controller so that the then implementation is in controller itself. Commented Nov 2, 2018 at 8:18
  • thanks Ankit Agarwal. I think other solution. Commented Nov 2, 2018 at 9:17

1 Answer 1

0

You're thinking of async call to be accomplish in sync way. That won't happen, you have to wait until the ajax call is done, you can easily make this happen using promise.

angular.module("app")
.factory("service", function ($http) {
    var allDataMap = {};
    // create a promise
    var promise = $http({
        method: 'GET',
        url: '/data'
    }).then(function (response) {
        angular.forEach(response.data.datas, function (value) {
            allDataMap[value.key] = value.value;
        });
        return allDataMap;
    });


    return {
        convertValue: function (key) {
            // wait until promise finish 
            return promise.then(function() {
               return key + '(' + allDataMap[key] + ')';
            });
        },  
    };
});
Sign up to request clarification or add additional context in comments.

Comments

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.