I want to make the currently logged in user's ID and user name available to my Angular directives. I have created an API end-point to retrieve this information (along with some other information).
The problem is that the API call is asynchronous:
var url = baseUrl + 'api/sessions';
$http.get(url)
I am trying to create a factory that will return the JSON object returned by the API. However, since the call is asynchronous, I don't know how to implement the factory method.
Additionally, I don't want to instantiate the directives until after the value comes back from the API. Is there a mechanism built in to AngularJS that will make sure the asynchronous call has returned first, or should I just create a global object and update its values when the call returns (using the JSON object)?
This is what I currently have:
application.factory('session', ['$http', 'baseUrl', function ($http, baseUrl) {
var session = {};
var url = baseUrl + 'api/sessions';
var promise = $http.get(url)
.success(function (data) {
for (var key in data) {
session[key] = data[key];
}
});
return session;
}]);
The problem is that any dependent directives are retrieving the session object before it is populated. I am concerned that if the API call takes a long time, the session object will be uninitialized when the user goes to use it.