第一次服务完成后运行Angular Service

时间:2015-11-09 20:50:06

标签: javascript angularjs cookies

我有两个Angular服务。第一个创建cookie,第二个设置URL以包含创建的cookie。我需要第一个在第二个之前运行。通常这在使用服务时不是问题,因为我的服务倾向于使用具有成功输出的http调用,但在这种情况下,我没有成功通话,我不知道我是怎么做的可以触发第一个完成。这是我的代码:

// Set Session Cookie
appCheckCookie.getCookie();

// Get Cart URL with Session Cookie
$scope.cartURL = appCartURL.getCartURL();

我已经尝试将它们包装在自己的函数中并尝试按顺序执行它们,但这并不起作用。我试过这样的事情,但它没有工作:

appCheckCookie.getCookie(function(){
$scope.cartURL = appCartURL.getCartURL();
});

以下是我的两项服务:

appServices.factory('appCheckCookie', ['$http', function ($http) {
    var getCookie = function () {

        // Create session cookie
        function createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        }

        // Function to read cookie
        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        var x = readCookie('ppkcookie')

        if (x == null) {

            // Get Session ID from backend URL
            $http.post('/getSession', {}).success(function (data) {

                // Create cookie from session ID from backend. Note that setting the days to 0 deletes the cookie on browser close (recommended)
                createCookie('ppkcookie', data, 0);
                console.log("Cookie Created: " + data);
            }, function (err) {
                console.log(err);
            });
        }

        else {
            var data = readCookie('ppkcookie');
            console.log("Cookie Exists: " + data);
        }
    };

        return {
            getCookie: getCookie
        };
}]),

appServices.factory('appCartURL', ['$http', function ($http) {
    var getCartURL = function () {

        // Function to read cookie
        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        var x = readCookie('ppkcookie')
        var baseCartURL = 'http://myecommsite.net/basket.html?Session_ID='
        var cartURL = baseCartURL + x;
        return cartURL;
    };

    return {
        getCartURL: getCartURL
    };
}]),

2 个答案:

答案 0 :(得分:1)

如果处理异步操作,Promise应该是要考虑的API之一。 What is Promise? 这可能会为您提供一些如何在您的案例中使用它的灵感:

// Namespace YourService
function readCookie(name) {
    return new Promise(function(resolve, reject){
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) 
                resolve(c.substring(nameEQ.length, c.length));
        }

        resolve(null); // consider reject(null)?
    });
}

// Run in service

YourService.readCookie(name).then(function(cookieResponse) {
    // Run your second service after cookie retrieved
}).catch(function(reason) {
    // Catch reject
});

需要提及的另一件事是IE本身不支持Promise(当然它不...),所以要在IE中使用它,你需要应用polyfill

希望这可以提供帮助。

答案 1 :(得分:0)

关于使用$ q的好建议。与同事一起,这是有效的,因为我们只需要第一个服务来表示它已完成:

appServices.factory('appCheckCookie', ['$q', '$http', function ($q, $http) {
    var getCookie = function () {
        var deferred = $q.defer();
        // Create session cookie
        function createCookie(name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else var expires = "";
            document.cookie = name + "=" + value + expires + "; path=/";
        }

        // Function to read cookie
        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

        var x = readCookie('ppkcookie')

        if (x == null) {

           // Get GUID for the cookie               
           $http.post('/getSession', {}).success(function (data) {

                // Create cookie. Note that setting the days to 0 deletes the cookie on browser close (recommended)
                createCookie('ppkcookie', data, 0);
                console.log("Cookie Created: " + data);

                deferred.resolve(data);

            }, function (err) {
                console.log(err);
            });
        }

        else { 
                var cookieExists = readCookie('ppkcookie');
                console.log("Cookie Exists: " + cookieExists);

                deferred.resolve(cookieExists);
        }

        return deferred.promise;
    };

        return {
            getCookie: getCookie
        };
}]),

然后在控制器中:

appCheckCookie.getCookie().then(function (data) {

    // Get Cart URL
    $scope.cartURL = appCartURL.getCartURL();
    console.log($scope.cartURL);
});