0

I am having an issue with login timing in an angular app. My intention is that when a user logs in, that the API key is then set in localStorage and is available to call on for accessing the API. After login, I want the app to redirect the user to the home state. But what is happening is that the user is redirected, gets a 401 - and based off what I have setup - is then redirected back to login. If I do a hard refresh on the browser after logging in it works. Here is what I have going.

.factory('localStor', function($q, $log, $window, $rootScope) {
var apiKey = false;

return {
    getAPI: function() {
        return $q(function(resolve, reject) {
            var data = $window.localStorage.getItem('apiKey');

            if (data == null) {

                return $rootScope.$broadcast('notAuthorized');
            } else {
                var key = data;
                return resolve(key);

            }

        });
    },
    setAPI: function(key) {
        return $q(function(resolve, reject) {
            apiKey = false;
            if (key === undefined) {
                return reject();
            }

            return $window.localStorage.setItem('apiKey', key);
        });
    }
}


})

function getLogin(email, password) {
    return $q(function(resolve, reject) {
        $http({
            method: 'POST',
            data: {
                'email': email,
                'password': password
            },
            url: config.api.baseUrl + '/user/login'
        }).then(function(result) {
            if (result) {
                var token = result.data.data.token;
                resolve(token);
            } else {
                $log.debug('Incorrect email or password');
                reject(1);
            }
        }, function(reason) {
            reject(2);
        });

    })
}

$scope.submitLogin = function(email, password, form) {

    $scope.errorNote = false;

    if (form.$valid) {
        $scope.loading = true;
        login.getAPI(email, password).then(function(data) {
            var key = data;
            localStor.setAPI(key).then(function() {
                $timeout(function() {
                    $state.go('app.loading', {}, { reload: true });
                }, 30);
            });
            $scope.loading = false;


        }, function(reason) {
            $scope.errorNote = reason;
            $scope.loading = false;
        });

    }
};

My calls to the API are then set up like this

var apiKey = false;
localStor.getAPI().then(function(data) {
    apiKey = data;
    $log.debug(apiKey);
}, function() {
    $rootScope.$broadcast('notAuthorized');
});

function withApiKey(callback, errorcallback) {
    localStor.getAPI().then(function(data) {
        if (typeof callback === 'function') {
            callback(data);
        }
    }, function(err) {
        if (typeof errorcallback === 'function') {
            errorcallback(err);
        }
    });
}

function notificationCount() {
    return $q(function(resolve, reject) {
        withApiKey(function(key) {
            $http({
                method: 'GET',
                headers: { 'Authorization': 'Bearer ' + key },
                url: config.api.baseUrl + '/user/notifications/count'
            }).then(function(result) {
                if (result) {
                    resolve(result);
                } else {
                    reject('Uh Oh');
                }
            }, function() {
                reject('Uh Oh');
            });
        });
    })
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
user641957
  • 49
  • 1
  • 6

2 Answers2

0

Is this a $q(resolve, reject) Anti-Pattern?

Using $q(resolve, reject) with the $http service is another example of the $q defer anti-pattern. It is unnecessary and prone to erroneous implementation.

Simply return the $http promise. Use its .then method to transform the response:

function getLogin(email, password) {
    ̶r̶e̶t̶u̶r̶n̶ ̶$̶q̶(̶f̶u̶n̶c̶t̶i̶o̶n̶(̶r̶e̶s̶o̶l̶v̶e̶,̶ ̶r̶e̶j̶e̶c̶t̶)̶ ̶{̶
    ͟r͟e͟t͟u͟r͟n͟ $http({
            method: 'POST',
            data: {
                'email': email,
                'password': password
            },
            url: config.api.baseUrl + '/user/login'
        }).then(function(result) {
            if (result) {
                var token = result.data.data.token;
                ̶r̶e̶s̶o̶l̶v̶e̶(̶t̶o̶k̶e̶n̶)̶;̶
                ͟r͟e͟t͟u͟r͟n͟ token;
            } else {
                $log.debug('Incorrect email or password');
                ̶r̶e̶j̶e̶c̶t̶(̶2̶)̶;̶
                ͟t͟h͟r͟o͟w͟  1;
            }
        }, function(reason) {
            ̶r̶e̶j̶e̶c̶t̶(̶2̶)̶;̶
            ͟t͟h͟r͟o͟w͟  2;
        });
    })
}

The .then method returns a new promise that settles to what the respective handlers either return or throw.

For more information, see You're Missing the Point of Promises.

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95
0

Ended up being a variable mismatch. The above promise structure worked well once the mismatch was taken care of.

user641957
  • 49
  • 1
  • 6