dpf71390 2014-10-15 16:45
浏览 150
已采纳

API调用后的Angular回调

I have an angular app but sometimes my callbacks seem to execute before they should. I have defined an service for my api calls, its methods look like this.

    function addOffer(id) {
        var request = $http({
            method: "get",
            url: "/api/campaign/offers",
            params: {
                action: "add",
                id: id
            }
        });
        return ( request.then(handleSuccess, handleError) );
    }
    function handleError(response) {

        // The API response from the server should be returned in a
        // nomralized format. However, if the request was not handled by the
        // server (or what not handles properly - ex. server error), then we
        // may have to normalize it on our end, as best we can.
        if (
            !angular.isObject(response.data) || !response.data.message
        ) {

            return ( $q.reject("An unknown error occurred.") );

        }

        // Otherwise, use expected error message.
        return ( $q.reject(response.data.message) );

    }

    function handleSuccess(response) {
        return ( response.data );

    }

And then in my controller I have scope functions defined like this

$scope.addOffer = function(){
    campaignService.addOffer($scope.id).then(
        loadRemoteData()
    );
};

The load remote data function syncs the client with what is stored in the application backend.

My problem is that in the controller method addOffer, the loadRemoteData() function fires before the offer is added, so that it loads the data without the new offer. But then upon a forced refresh that offer is there. Is there something that needs to be done differently so that this will work as expected?

  • 写回答

1条回答 默认 最新

  • douxie7339 2014-10-15 17:18
    关注

    The problem is with () in loadRemoteData(). No matter where you do this, the loadRemoteData() function will be actually executed. If you just want to pass loadRemoteData function as a success callback to .then() then you should simply pass the name of the function.

    Change your controller code to:

    $scope.addOffer = function(){
        campaignService.addOffer($scope.id).then(loadRemoteData);
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试