0

I have this authentication service, that checks if the user has a Session stored. and if it get's the info from the api by returning the $http.post():

authService.getUser = function () {
    if (!SessionService.get('Auth')) return null;

    $userId = SessionService.get('User');
    SessionService.set('Auth', false); // reset to false

    if ($userId == null) return null;


    return $http.get('/api/users/' + $userId)
        .success(function (res) {
            SessionService.set('Auth', true);
            return res;
        })
        .error(function () {
            return null;
        });
}

and this is called like following:

AuthenticationService.getUser()
    .success(function (res) {
        $scope.user = res;
        console.log(res);
    })
    .error(function () {
        Materialize.toast('You are not logged in!');
    });

but this fails ofcourse when it doesn't have a session stored, because I return null.

So how would you change the service that the return null triggers the error()

1 Answer 1

4

Simply return a rejected promise:

return $q.reject();

Note that your .error(...)is completely useless.

Also note that since you won't return an HTTP promise, but a regular $q promise, the caller shouldn't use .success() and .error(). It should call .then() and .catch().

Sign up to request clarification or add additional context in comments.

4 Comments

yea the error is useless, because I'm still figuring out how to return the rejection so the error is triggerd :) (looking into the $q.reject(); thingy)
Just remove the .error(). Your service returns the http promise, which will be rejected if the server returns a 4xx or 5xx response, causing the toast to appear.
ow the error in the $http, yea that one is useless :p but i get a $q is not defined
@Kiwi inject the $q service into your controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.