KingJulian
KingJulian

Reputation: 973

AngularJS resolve an AJAX request with arbitrary data w/o making an AJAX call

I have a service that calls a URL for fetching details of a user.

...
this.getUserDetail = function (userId) {
    // deal cache
    var request = $http({
        method: "get",
        url:    "/users/"+userId
    });
    return request.then(successFn, errorFn);
};

But at another place, I am fetching the user details too and creating a map of newly fetched users. I want to reuse an already fetched user from my JavaScript object.

this.getUserDetail = function (userId) {
    if (userMap[userId]) {
        return $q.resolve({
            'result': userMap['userId']
        });
    }
    var request = $http({
        method: "get",
        url:    "/users/"+userId
    });
    return request.then(successFn, errorFn);
};

But this doesn't work. I have included $q. I don't get JavaScript errors, except that at a place where I am using this.getUserDetail(userId).then(..., it throws error, as I am may be not returning a succesFn from the way I am doing it.

Am I doing it properly?

Upvotes: 0

Views: 242

Answers (3)

Om Shankar
Om Shankar

Reputation: 8069

The function that you call is using AJAX.

Now from your question, since you are using then, this.getUserDetail(userId).then(), it means getUserDetail must return a promise itself.

Now if I understand it correctly, you want to resolve a promise with random data, without making AJAX call when an item is cached. In that case, make your function to conditionally use promise object.

this.getUserDetail = function (userId) {
    var cachedUser = userMap(userId),
        deferredData = $q.defer();

    var request = cachedUser ? deferredData.promise : $http({
        method: "get",
        url: "/users/" + userId
    });

    if (cachedUser) {
        deferredData.resolve({
            'data': {
                'result': cachedUser
            }
        });
    }

    return request.then(successFn, errorFn);
};

Edit:

And then use it in your controller as:

this.getUserDetail.then(function(response){
    // this response object is same object with which
    // promise was resolved. 
    // Doesn't matter whether the promise was AJAX or your own deferred.
});

Doesn't matter whether the promise was AJAX or your own deferred.

Upvotes: 2

Steve Lang
Steve Lang

Reputation: 559

this.getUserDetail = function (userId) {
    if (userMap[userId]) {
        return $q.when(userMap[userId]);
    } else { 
        return $http({
            method: "get",
            url:    "/users/"+userId
        })
        .then(function (result) {
            // add to userMap;
            return result;
        });
    }
};

Upvotes: 0

Marian Ban
Marian Ban

Reputation: 8168

You can use AngularJs built in cache:

var request = $http({
    method: "get",
    url:    "/users/"+userId,
    cache: true
});

Upvotes: 0

Related Questions