工厂和服务的依赖性错误

时间:2016-01-04 15:46:48

标签: javascript angularjs

使用factory我通过ApiRequest.sendRequest向我的API获取用户信息:

(function() {

angular.module('isApp.user', [])

.factory('UserProfileFactory', function( $log, ApiRequest, dataUrls ) {

    var userProfile = {
        token : null,
        id : null,
        name : null,
        ifMode : null,
        justReader : true,
        debugApp : 'NO',
        didTutorial : false,
        showOnlyUnread : true,
        markAsReadOnScroll : false,
        tagLimit : null,
    };

    return {
        logIn : logIn,
        setConfigByAuthentication : setConfigByAuthentication,
        getUserProfileFromDevice : getUserProfileFromDevice,
        getUserProfile : getUserProfile,
        setDefaultUserProfile : setDefaultUserProfile,
        saveUserProfile : saveUserProfile,
        // Getters & Setters
        setToken : setToken,
        getToken : getToken,
        setId : setId,
        getId : getId,
        setName : setName,
        getName : getName,
        setIfMode : setIfMode,
        getIfMode : getIfMode,
        setJustReader : setJustReader,
        getJustReader : getJustReader,
        setDebug : setDebug,
        getDebug : getDebug,
        setDidTutorial : setDidTutorial,
        getDidTutorial : getDidTutorial,
        setShowOnlyUnread : setShowOnlyUnread,
        getShowOnlyUnread : getShowOnlyUnread,
        setMarkAsReadOnScroll : setMarkAsReadOnScroll,
        getMarkAsReadOnScroll : getMarkAsReadOnScroll,
        getTagLimit : getTagLimit
    };


    function logIn( user, passwd )
    {
        var config = {
            method: 'POST',
            url: dataUrls.main + dataUrls.login,
            headers: 
            {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            transformRequest: 
                function(data) 
                {
                    var str = [];
                    for( var attr in data )
                        str.push(encodeURIComponent(attr) + "=" + encodeURIComponent(data[attr]));
                    return str.join("&");
                },
            data: 
            { 
                username: user,
                passwd: passwd
            }
        };

        $log.info('Login Request START -url-', config.url);
        return ApiRequest.sendRequest( config ).then( 
            function (response)
            {
                if (response != undefined )
                {
                    if (response.status == 200)
                    {
                        userProfile.token = response.data.token;
                        userProfile.id = response.data.userData.id;
                        userProfile.name = response.data.userData.name;
                        userProfile.ifMode = response.data.ifmode;
                        userProfile.justReader = response.data.rights.just_reader;
                        userProfile.debugApp = response.data.debugApp;
                        userProfile.didTutorial = false;
                        userProfile.showOnlyUnread = true;
                        userProfile.markAsReadOnScroll = false;
                        localStorage.isAuthenticated = true;
                        userProfile.tagLimit = response.data.tagLimit;
                        saveUserProfile();
                        return response.status;
                    }
                }
                return response;
            },
            function (response)
            {
                return response;
            }
        );
    }

    function setToken(value)
    {
        userProfile.token = value;
        saveUserProfile();
    }

    function getToken()
    {
        return userProfile.token;
    }


});
})();

service使用两个函数sendRequestsendsend需要使用函数UserProfileFactory.getToken()获取用户令牌。

拥有sendsendRequest的原因是我们首先使用sendRequest,但我们想要开始使用send,但我们仍在进行更改代码和变化可能是敏感的,我们仍然想要保持两者。在示例中,我们使用sendRequest,但在代码的其他部分,我们使用send但不在工厂中,我们只使用sendRequest,如您所见。

(function() {

angular.module('isApp.api', [])


.service('ApiRequest', function($http, $log, $q, UserProfileFactory, toaster, LanguageTexts, dataUrls) {

    this.sendRequest = sendRequest;
    this.send = send;

    function send( request )
    {   
        if (request.method == undefined) request.method = 'GET';

        if (request.header != undefined)
        {
            request.headers['Authentication'] = 'Token ' + UserProfileFactory.getToken();
        }
        else
        {
            request.headers = {};
            request.headers['Authentication'] = 'Token ' + UserProfileFactory.getToken();       
        }

        request.url = dataUrls.main + '/' + request.url;

        $log.info('Object request', request);
                return $http( request ).then( 
            function( response )
            {
                var APIResponse = response.data;
                if (typeof APIResponse != 'object')
                {
                    return $q.reject(response);
                }

                if (APIResponse.status == 200)
                {
                    return APIResponse.data;
                }
                else
                {
                    return $q.reject(response);
                }
            },
            function( response )
            {
                $log.error('HttpError: ', response.status);
                $log.error('Response complete: ', response);
                toaster.pop('error', null, LanguageTexts.errorServerError);
                return $q.reject(response);
            }       
        );
    }

    function sendRequest( request )
    {
        return $http( request ).then( 
            function( response )
            {
                $log.info('HttpResponse: ', response.data.status);
                $log.log('Response Data: ', response.data);
                if (response.data.status == undefined)
                {
                    $log.info('Response undefined: ', response);
                }
                if ( response.data.status != 200 )
                {
                    return response.data.status;
                }
                return response.data;
            },
            function( response )
            {
                if ( response.config.timeout != undefined )
                {
                    if ( response.config.timeout.$$state.value != undefined )
                    {
                        $log.warn('HttpError: ', response.status);
                        $log.warn('Promise cancel: ', response.config.timeout.$$state.value);
                        return "promise_cancel"; 
                    }
                }
                $log.error('HttpError: ', response.status);
                $log.error('Response Error Data: ', response);
                return response;
            }       
        );
    }

}]);
})();

我得到了经典的循环依赖错误:

Error: [$injector:cdep] http://errors.angularjs.org/1.3.13/$injector/cdep?p0=UserProfileFactory%20%3C-%20ApiRequest%20%3C-%20UserProfileFactory

有人可以告诉我如何重新排序我的两个文件以避免出现依赖性错误?提前谢谢。

1 个答案:

答案 0 :(得分:1)

不是重新排序您的组件,它在结构上是不可能的:如果需要创建ApiRequest来创建UserProfileFactory,反之亦然,AngularJS&#39}解析器永远不能满足创建任何依赖项。

检查您的依赖项,看看您是否可以采用不同的方式构建代码:A <> B的依赖关系是否可以使用C作为A > C < B重新编写? C具有AB都需要的功能。