如何正确链接Angular HttpPomise



我有一个带功能的角度服务:

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

我需要在发送返回值之前对其进行操作,并且我希望保持HttpPromise结构的完整性,因为我的控制器代码是为了期望HttpPromise的成功和失败函数存在而编写的。

我已经将服务改写为这样:

    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;
    };

无论我是返回hp还是返回newHP,此代码都能正常工作。我的问题是:这是HttpPromise链接的正确形式吗?

调用.success返回与其调用时相同的延迟对象。它不会创建新对象。它所做的只是在deferred上注册一个success回调。

你可以使用新的参考,或者只保留旧的参考:

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;
};

如果你想,你可以把它们全部链接起来,然后直接返回延迟的对象:

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");
    });
};

最新更新