Angular服务在回调函数中部分可用

时间:2015-12-10 10:24:10

标签: javascript angularjs callback angularjs-service

在我的角度简单应用程序中,我遇到了一个在回调函数中无法完全使用的工厂的问题。

Here is a plnckr,其中包含应用程序的简化版本。

这是我的代码:

控制器:

    function activate() {

        return featureService.getBoards().then(callBackOk, callBackError);

        function callBackOk(data) {
            vm.boards = data;
        };

        function callBackError(error) {
            console.log(error);
        };
    };

featureService:

function getBoards() {

        return connectionService.get(urls.featureUrl).then(callBack, callBackError);

        function callBack(response) {

            boards = {};
            actuators = [];

            response.data.forEach(function(feature){
                formatFeature(feature);
                storeFeature(feature);
            });

            return boards;
        }

        function callBackError(error) {
            var deferred = $q.defer();

            console.log(angular.toJson(loginService.issue));
            console.log(angular.toJson(loginService.isOk));
            console.log(angular.toJson(loginService.error));
            console.log(angular.toJson(loginService));

            loginService.issue("Unable to retrieve objects", error).then(function(){
                deferred.resolve(getBoards());
            }, function(error){
                deferred.reject(error);
            });

            return deferred.promise;
        }
    }

控制台记录:

undefined features.services.js:71:1
undefined features.services.js:72:1
{"label":"","detail":{}} features.services.js:73:1
{"error":{"label":"","detail":{}},"graphicDefered":{}} features.services.js:74:1
Error: loginService.issue(...) is undefined
    callBackError@http://localhost:8100/app/features/features.services.js:76:17

最后,来自loginService的返回对象:

    return {
        'login'     : login,
        'logout'    : logout,
        'isOk'      : function(){return ok;},
        'issue'     : issue,
        'error'     : error,
        'graphicDefered' : graphicDefered
    };

我假设get方法会抛出一个由callBackError函数拦截的异常。我怀疑是懒惰的装载机,但我不知道如何解决它......

1 个答案:

答案 0 :(得分:1)

undefined features.services.js:71:1
undefined features.services.js:72:1

这两个不信任是因为你在函数上调用angluar.toJson。只需尝试console.log(loginService.issue),它就会打印出来。

如果(detail.status === 403 || detail.status === 401)为true,函数问题只返回login(promise),否则返回undefined,然后你就无法调用undefined。

    function issue(label, detail) {
        error.label = label;
        error.detail = detail;

        if (detail.status === 403 || detail.status === 401) {
            ok = false;

            return login(account.mail, account.pwd);
        }
    }