Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

javascript - How to correctly chain Angular HttpPomise

I had an angular Service with a function:

    service.getItemByID = function(id) {
        var hp = $http({method: "GET", url: "service/open/item/id",
            headers: {"token": $rootScope.user.token},
            params: {"id": id}});

        return hp;
    };

I need to manipulate the returned values before sending them on and I want to keep the HttpPromise structure intact since my controller code is written to expect the success and failure functions of the HttpPromise to be present.

I have rewritten the service to look like this:

    service.getItemByID = function(id) {
        var hp = $http({method: "GET", url: "service/open/item/id",
            headers: {"token": $rootScope.user.token},
            params: {"id": id}});

        var newHP = hp.success(
                function(data, status, headers, config) {
                    data.x = "test";  //TODO: add full manipulation
                    alert("success");
                    return hp;
                });

        return newHP;
    };

This code works and it work regardless of whether I return hp or newHP. My question is: Is this a proper form of HttpPromise chaining?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Calling .success returns the same deferred object that it was called on. It does not create a new object. All it does is register a success callback on the deferred.

You can use the new reference, or just keep the old reference:

service.getItemByID = function(id) {
    var hp = $http({method: "GET", url: "service/open/item/id",
        headers: {"token": $rootScope.user.token},
        params: {"id": id}});

    hp.success(
            function(data, status, headers, config) {
                data.x = "test";  //TODO: add full manipulation
                alert("success");
                return hp;
            });

    return hp;
};

If you want to, you could just chain them all, and return the deferred object directly:

service.getItemByID = function(id) {
    return $http({
        method: "GET",
        url: "service/open/item/id",
        headers: {"token": $rootScope.user.token},
        params: {"id": id}
    })
    .success(function(data, status, headers, config) {
        data.x = "test";
        alert("success");
    });
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...