I have a bizarre issue happening in my Angular app and I think the async'ness of Angular is the cause but I'm not sure how I can fix it.
On .run I have the following:
app.run(function ($user, $soundcloud) {
$user.set();
$soundcloud.set();
});
and then the two services...
app.service('$user', ['$http', function ($http) {
var currentUser;
this.set = function () {
$http.get('/users/active/profile')
.success(function (obj) {
currentUser = obj;
})
.error(function () {
console.log('ERR');
})
}
this.fetch = function () {
return currentUser;
}
}]);
app.service('$soundcloud', ['$http', function ($http) {
var sc;
this.set = function () {
$http.get('/users/active/services/soundcloud')
.success(function (obj) {
sc = obj;
})
.error(function () {
console.log('Error fetching soundcloud feed')
})
}
this.fetch = function () {
return sc;
}
}]);
The issue I'm having is that when I go to /profile and reload the page, the data returned from $soundcloud.fetch() isn't available unless I wrap $soundcloud.fetch() inside a setTimeout() function which obviously isn't ideal so I'm wondering where I should place $soundcloud.set() to also make that data available immediately on page load.
This is my controller currently:
app.controller('profileController', ['$scope', '$user', '$soundcloud', function ($scope, $user, $soundcloud) {
$scope.activeUser = $user.fetch();
$scope.activeSoundcloud = $soundcloud.fetch();
console.log($user.fetch());
setTimeout(function () {
console.log($soundcloud.fetch());
},100);
}]);
If I take $soundcloud.fetch() outside of the setTimeout then I get undefined as the result. Where should $soundcloud.set/fetch be called in order to make both sets of data (user and soundcloud) immediately available?
$soundcloud.set()and$user.set()invoked only during the.run()phase?