Growler Growler - 5 months ago 12
AngularJS Question

How can I return a called back function?

I using Angular's

$http
to get questions, which expects a promise in return, either
success
or
error
:

Question.getQuestions().success(function (res) {
...
}).error(function (err) {});


In my method, I need to check if token is expired, if so, refresh, then make the request to
/questions
and return the promise. Otherwise, just make the request to
/questions
as usual:

getQuestions: function() {

// this is called by refreshToken but not returning the $http promise
var get = function() {
return $http({
method: 'GET',
url: url + ver + '/questions',
...
});
};

if (Auth.tokenIsExpired()) {
return Auth.refreshToken(get);
} else {
return get();
}
},


The refreshToken is another
$http
which relies on a promise, then calls the
get()
callback.

Auth {...

refreshToken: function(callback) {
...
_this.getAuth(OAuth).success(function (access_obj) {
//set token
callback();
})...


Where getAuth is another
$http promise
:

getAuth: function(params) {
return $http({
method: 'POST',
url: url + '/oauth/access_token',
...
});
},


All of these methods are called as expected, but am getting error:

Cannot read property 'success' of undefined


This is because
Auth.refreshToken(get)
is not returning the
/questions $http
call as it should. How can I return the promise from that back to the original
Question.getQuestions()
?

Answer

Here's a suggestion since your code looks over-complicated.

getQuestions: function() {   
    var get = $http({
        method: 'GET',
        url: url + ver + '/questions',
        ...
    }); 
    if (Auth.tokenIsExpired()) {
        return Auth.refreshToken().then(function(){
         return get();
        });
    } else {
        return get();
    }
}

refreshToken: function() {
    return _this.getAuth(OAuth).then(function (access_obj) {
        //set token
    });
}

Basically refreshToken should refresh the token and return a promise for when its done. Then when you GET the questions you check if the token is expired, if it did then you call refreshToken and when its done (.success()/.then() is called you do the usual GET)

You can simplify this further and let Auth handle all of the token refreshing for you by moving the line Auth.tokenIsExpired() inside the refreshToken method.

Another example:

getQuestions: function() {    
    return Auth.refreshToken().then(function(){
         return $http.get(url + ver + '/questions');
    });
}

refreshToken: function() {
    if (_this.tokenIsExpired())
     return _this.getAuth(OAuth).then(function (access_obj) {
        //set token
    });
    else return $q.resolve(/*value needed?*/);
}
Comments