Reputation: 495
First here's my code below. My main problem is I can't return the result data outside my invokeConfigFile function after invoked or after ajax call.
var invokeConfigFile = function() {
return $http.get('json/config.json');
};
var data = {}
var getDataFromInvokedFile = function() {
invokeConfigFile().then(function(result) {
var current_env = result.data.current_environment,
list_env = result.data.environments;
angular.forEach(list_env, function(value, key) {
// retrive the config on the current environment
if(key === current_env) {
data = value;
return false; //let's stop if the condition are met
}
});
console.log(data); // return data GOOD
return data;
}, function(result) {
if(result.status == 404) {
alert("Server config.js file not found.");
return false;
}
});
console.log(data); // return data EMPTY
};
var my_urls = getDataFromInvokedFile();
What I'm trying to accomplish here is after I get the result data from my ajax call which is invokeConfigFile(), I will then store this to an object.
Something like this
return {
my_obj : getDataFromInvokedFile()
}
Upvotes: 0
Views: 94
Reputation: 142
i make some change so comment "check here"
var getDataFromInvokedFile = function() {
invokeConfigFile().then(function(result) {
var current_env = result.data.current_environment,
list_env = result.data.environments;
angular.forEach(list_env, function(value, key) {
// retrive the config on the current environment
if(key === current_env) {
data = value;
return false; //let's stop if the condition are met
}
});
console.log(data); // return data GOOD
return data;
}, function(result) {
if(result.status == 404) {
alert("Server config.js file not found.");
return false;
} console.log(data); // check here
});
};
Upvotes: 0
Reputation: 700680
You can't return the data from the function, as the AJAX call is asynchronous. The response arrives after the function returns.
Use a callback to handle the data when it arrives:
function getDataFromInvokedFile(callback) {
invokeConfigFile().then(function(result) {
var current_env = result.data.current_environment,
list_env = result.data.environments;
angular.forEach(list_env, function(value, key) {
// retrive the config on the current environment
if(key === current_env) {
data = value;
return false; //let's stop if the condition are met
}
});
callback(data);
}, function(result) {
if(result.status == 404) {
alert("Server config.js file not found.");
calback(false);
}
});
}
Usage:
getDataFromInvokedFile(function(data){
// here you have the data
});
Upvotes: 2