使用factory可以通过对我的API进行ApiRequest.sendRequest来获取用户信息:

(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


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

最佳答案

这不是要重新排列组件,在结构上是不可能的:如果需要创建ApiRequest来创建UserProfileFactory,反之亦然,AngularJS的解析器将永远无法满足创建两者的依赖。

查看您的依赖关系,看看是否可以以不同的方式构造代码:A <> B的依赖关系是否可以用新的组件C重写为A > C < BC具有AB都需要的功能。

关于javascript - 工厂和服务的相关性错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34594803/

10-10 23:10