I am currently facing an issue with my Controller and Factory. The Controller initiates an API call in the Factory, but I am struggling to make it wait for the data to be gathered before proceeding. This is where I believe implementing something like $q
might be necessary.
In the code snippet below, you can see that vs.tickers
initially returns an empty object or array, and only after a while does the console.log
in GetTickersFactory execute:
1st Controller
if (root.tickerType === 'portfolio') {
// Initiating the API GET request in the factory:
GetTickersFactory.getTickers('portfolio');
// Calling a function in the Factory to retrieve the array
// However, since the data is not ready yet, it returns undefined...
vs.tickers = GetTickersFactory.returnPortfolioTickers();
console.log('portfolio');
console.log('vs.tickers = ', vs.tickers);
}
getTickers function in the GetTickersFactory | For more details: check out the full Factory on Gist.
function getTickers(type, load, searchedTicker) {
load = load || loadString; searchedTicker = searchedTicker || '';
var portfolioTickersArray = [], searchedTickersArray = [];
tickersPane.loadingTickersDone = false;
switch(type) {
case 'searched':
....
break;
case 'portfolio':
if (portfolioCached) {
// Making the API Call using cache
ApiFactory.getWatchList().then(function(data) {
portfolioTickersArray = renderTickers(data.data.tickers, undefined, type);
portfolioTickers.that = portfolioTickersArray;
tickersPane.loadingTickersDone = true;
console.log('portfolioTickersArray: ', portfolioTickersArray);
return portfolioTickersArray;
});
} else {
// Making the API Call without cache
ApiFactory.getWatchListRefresh().then(function(data) {
portfolioTickersArray = renderTickers(data.data.tickers, undefined, type);
portfolioTickers.that = portfolioTickersArray;
portfolioCached = true;
tickersPane.loadingTickersDone = true;
console.log('portfolioTickersArray: ', portfolioTickersArray);
return portfolioTickersArray;
});
}
break;
}
function renderTickers(data, searchedTicker, type) {
....
}
}
The return Array function within the getTickersFactory.js | I suspect I should find a way to use promises here instead of relying on this method:
function returnPortfolioTickers() {
return portfolioTickers.that;
}
I did attempt the following previously, with no success:
vs.tickers = GetTickersFactory.getTickers('portfolio');
vs.tickers
would still end up as undefined