简体   繁体   中英

using angular factory with $http

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] + ')';
        },  
    };
});

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] + ')';
            });
        },  
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM