I've written an AngularJS factory, profileService
, that handles setting/getting user profile info. Its getProfile
method calls my web API, is returned a JSON object with the user's data, and resolves the $http.get
promise with that data. This particular promise is being used in a login
method which is a member of an authentication factory. The block of code within login
is in the midst of returning its own $http.post
promise (it's requesting a token). The idea is to retrieve and locally cache the user's profile data upon login.
The issue is that the $http.get
promise is resolving too late. That is, in my console output, the call shows as resolving to nothing (undefined
), immediately followed by getProfile
's inline output showing a successful profile object retrieval. Calling a variable that's stored the resolved promise also yields undefined
.
Based on my research, I'm leaning towards the issue being me not thinking about promises correctly. Any help in understanding where I went wrong is greatly appreciated!
Code: profileService.getProfile(userName):
profileService.getProfile = function(userName) {
return $http.get(ntSettings.apiServiceBaseUri + '/api/Profile/GetProfile?userName=' + userName)
.then(function(response) {
return response.data;
});
};
Code: authService.login() calling getProfile
var profileService = $injector.get('profileService');
var userProfile = {};
profileService.getProfile(loginData.userName)
.then(function(response) {
userProfile = response;
console.debug("authSvc -> login -> getProfile: Got profile data:", response.userProfile);
}, function(error) {
console.error("authSvc -> login: Unable to fetch profile", error);
});
console.debug("authSvc -> login: Displaying profile object", response.userProfile);
Console debug output showing issues
authSvc -> login: Showing profile object: undefined
authSvc -> login -> getProfile: Got profile data: Object {FirstName: "John", LastName: "Doe", Birthday: "2015-05-06T04:00:00", Gender: 0, Location: "New York, NY"}