Tori Huang Tori Huang - 5 months ago 23
AngularJS Question

Receiving Resource object instead of value using Node and Angular

I am trying to get the value returned through an authorization getCurrentUser function. When calling the function, I get this resource holding a Promise. I can see the _id value in there! How do I access it?

Thank you in advance!
Console Output

Here's a bit of the Auth service where getCurrentUser is defined:

(function config() {
function AuthService($location, $http, $cookies, $q, appConfig, Util, User) {
const safeCb = Util.safeCb;
let currentUser = {};
let Auth = {};
const LOCAL_HOST = 'localhost';

if ($cookies.get('token') && $location.path() !== '/logout') {
currentUser = User.get();
}

Auth = {
getCurrentUser(callback) {
if (arguments.length === 0) {
return currentUser;
}

const value = currentUser.hasOwnProperty('$promise') ? currentUser.$promise : currentUser;
return $q.when(value).then(user => {
safeCb(callback)(user);
return user;
}, () => {
safeCb(callback)({});
return {};
});
}
...


Here is where I call it:

angular.module('toroApp').directive('csvreaderDirective', ['$http', function ($http, Auth) {

return {
controller(Auth) {
const currentUser = Auth.getCurrentUser();
console.log(currentUser);
},
compile(element, Auth) {
...

Answer

Auth.getCurrentUser() is returning a $q promise so you need to use the promise API to get the result.

controller(Auth) {
    Auth.getCurrentUser().then(function (user) {
        const currentUser = user;
        console.log(currentUser);
    });
}