devdropper87 devdropper87 - 1 month ago 8
AngularJS Question

trying to set value in promise .then returns undefined

I am new to angular 1.5, and used to rely on

for doing something like this, where I would bind the return value of a promise to the scope. I'm inside a service, and am trying to return data via a promise, and I want that data to then be exposed via this service. however, the data,
is undefined:

let mockData;
function getWidgets() {
return $http.get(`${RuntimeConfig.DEV_API_URL}/widgets`, { cache: widgetsCache })
getWidgets().then(function(data) {
mockData =;
console.log(mockData); //undefined.

return value of this service:

return {

my previous way to solve this would have been by declaring
, but I can't do that because a) it's an antipattern now b) i'm in a service. what am I doing wrong or missing?


mockData will be undefined since it get's returned even before your GET request finish. One way to handle this is to return the promise from the service and handle the promise resolution in let's say controller.