In my angular application there is function init(); which I called in starting to may javascript
then there is getMonthlyNews function which is called after init()
function init() {
configService.getResponders().then(function (data) {
apiUrl = data;
});
}
which is getting some setting from JSON file in local js/ folder
(function(){
app.factory("configService", ['$http', function ($http) {
return {
getResponders: function () {
return $http.get('assets/js/service/config.json')
.then(function (res) {
console.log("Data " + res.data.url);
return res.data.url;
});
}
};
}]);
})();
json file
{ "url":"http://localhost:6790//api/getNews/" }
function getMonthlyNews() {
var method = 'Search'
var url = apiUrl + method;
}
after calling init function in js file I need to get apiUrl form json file which is on local js folder using service
to get that value I have to call
when I call init function it takes time and return value after some time later but that time interval my function getMonthlyNews already executed with an undefined error so that I have to add a setTimeOut function like that
setTimeout(function () { getMonthlyNews(); }, 200);
so how to deal with this delay or any other idea
You are treating a promise wrongly. All code that assumes that the promise finishes should be in it's then function.
var promise;
function init() {
promise = configService.getResponders().then(function (data) {
apiUrl = data;
});
}
...
function getMonthlyNews() {
promise.then(function() {
var method = 'Search'
var url = apiUrl + method;
})
}
getting url should be done by using the new promise.