Currently, I am facing an issue with my API where the model variable is returning undefined before any data is populated in the return_array
.
I am unsure of how to implement promises or another method to ensure that the variable waits for data to be filled correctly, without resorting to using a less-than-ideal $timeout
hack.
The problem can be seen here in the chrome inspector (ticker_chart = undefined
):
https://i.sstatic.net/0x4JH.png
In this scenario, I require ticker_chart
to hold off until it receives a value.
The initial function responsible for calling out to a service to retrieve the ticker quote data:
function renderChart(ticker, limit) {
ticker_chart = TickerChartFactory.returnTickerChartData(ticker, limit);
console.log('ticker_chart = ',ticker_chart);
}
The complete service function is outlined below:
function returnTickerChartData(ticker, limit) {
var q = $q.defer();
var get_data = '';
if (limit > 0) {
get_data = '?limit=' + limit;
}
ApiFactory.getTickerQuotes(ticker.ticker).success(
function(data, status, headers, config) {
if (data.status == 'Success') {
console.log('REST GET Ticker Chart', 'success');
var data_array = [];
for (var i=0; i<data.quotes.length; i++) {
data_array.push([data.quotes[i].start_epoch, data.quotes[i].price]);
}
var return_array = [{
"area": true,
"key": "Price",
"color": '#BFBFBF',
"values": data_array
}];
console.log('return_array = ',return_array);
console.log('q =',q);
q.resolve(return_array);
return ticker_chart = return_array;
} else {
console.log('failed to REST GET Ticker Chart');
q.reject('failed to REST GET Ticker Chart');
return ticker_chart = 'failed to REST GET Ticker Chart';
}
}).error(function(data, status) {
console.log('error in getting REST GET Ticker Chart');
q.reject('error in getting REST GET Ticker Chart');
return ticker_chart = 'error in getting REST GET Ticker Chart';
});
}
The getTickerQuotes
function within the ApiFactory
:
function getTickerQuotes(ticker) {
return $http.get('https://www.ourapi.../api/tickers/quotes/'+ticker, {cache: false});
}
What would be the best way to utilize the promise in this context? One alternative approach could involve using a $scope.watch function to await the change in the value of ticker_chart
before attempting to render anything.