简体   繁体   English

API调用后的角度回调

[英]Angular callback after API call

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. 我已经为我的api调用定义了服务,其方法如下所示。

    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. 我的问题是,在控制器方法addOffer中,在添加要约之前会触发loadRemoteData()函数,以便它在没有新要约的情况下加载数据。 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? 是否需要做一些不同的事情才能使它按预期工作?

The problem is with () in loadRemoteData() . 问题是()loadRemoteData() No matter where you do this, the loadRemoteData() function will be actually executed . 无论您在何处执行, loadRemoteData()函数都会实际执行 If you just want to pass loadRemoteData function as a success callback to .then() then you should simply pass the name of the function. 如果您只想将loadRemoteData函数作为成功回调传递给loadRemoteData .then()则只需传递函数名称即可。

Change your controller code to: 将您的控制器代码更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM