My navbar has a "nav" controller that displays the current user's image. However, I'm facing an issue where the nav image does not update when the user changes their profile photo.
Below is my service:
'use strict';
angular.module('clientApp').factory('Account', function ($http, toastr) {
var currentUser = null;
function getUser(callback, user) {
console.log('get user user ', user)
// if the user has already been retrieved then do not do it again, just return the retrieved instance
if (currentUser !== null && currentUser !== user) {
callback(currentUser);
}
if (currentUser === null) {
// retrieve the currentUser and set it as a property on the service
$http.get('/api/me').then(function (res) {
// set the result to a field on the service
currentUser = res.data;
// call the callback with the retrieved user
callback(currentUser);
});
}
}
//updates the currentUser variable
function updateProfile(profileData, callback) {
console.log('profile data ', profileData);
$http.put('/api/me', profileData).then(function (res) {
currentUser = res.data;
callback(currentUser);
}).catch(function (response) {
if (response.data.message.length) {
for (var i = 0; i < response.data.message.length; i++) {
toastr.error(response.data.message[i]);
}
}
});
}
return {
getUser: getUser,
updateProfile: updateProfile
};
});
Watcher in the nav controller:
$scope.user = {};
//watches for currentUser changes in account service
$scope.$watch(Account.getUser(function(user){}, $scope.user), function (newValue, oldValue) {
console.log('user update watch', newValue)
$scope.user = newValue;
});
I seem to be confused about something here. I have been studying information on $watch, but it is not behaving as I anticipated. This could be because Account.getUser doesn't return anything for the $watch to compare, and instead uses a callback...
If anyone can help me identify where I am mistaken — I would greatly appreciate it.