角度嵌套承诺

时间:2015-06-25 21:36:08

标签: javascript angularjs promise

我真的很难在Angular中编写一个依赖于promises的复杂函数。这是我第一次写一个承诺,我仍然不确定我是否完全理解如何使用我的代码做我想做的事情。

我在控制器var query = searchQuery.getQuery()中有一个变量ProfileNavCtrl。然后在我的searchQuery服务中,getQuery获取localStorage.getItem('searchQuery')的值并检查它是否为空字符串或为空。如果它不为空或为null,它只是将值返回给控制器。该值应该是像['foo','foo-bar','foo-bar-baz']这样的slug数组。

如果它为null或为空,则执行$http.get调用以获取JSON对象并解析它。这就是我崩溃的地方。我需要getQuery()$http.get返回值(如果query的初始值为null),以便为控制器变量query分配该值。就像现在一样,query(在控制器中)始终设置为null或undefined。

$http.get调用也会调用setQuery(),以便保留查询并避免将来的调用。

这是我的控制器:

app.controller('ProfileNavCtrl', ['$scope', '$http', '$location', '$q', 'searchQuery',
function($scope, $http, $location, $q, searchQuery){
    var query = searchQuery.getQuery;
// do something with query

这是我的服务:

app.service('searchQuery', ['$http', '$timeout', '$q', function($http, $timeout, $q){
    var query = [];

    this.getQuery = new Promise(function(){
        var query = localStorage.getItem('searchQuery');

        if(query == "" || query == [""] || query == null){
            var slugArray = [];
            var query = $http.get('/companies.json')
            .then(function(resp) {
                if(resp && resp.data) {
                    for(var i in resp.data) {
                        var result = resp.data[i];
                        if(resp.data[i].name){
                            slugArray.push(resp.data[i].name.toLowerCase().split(' ').join('-'));
                        }
                    }
                    setQuery(slugArray);
                } else {
                    resetQuery();
                }
            }, function(err) {
                resetQuery();
            }).then(function(resp){
                return resp;
            })
            return query;
        } else {
            return query;
        };
    }).then(function(success){
        return success;
    });

更新:第二次尝试 这是我的控制器代码:     var getQuery = searchQuery.getQuery();

getQuery.then(function(query){
    query = searchQuery.getQuery();
    // Check if user is on main site or portal
    if(location.pathname.split('/')[3] == null){
        var currentProfile = location.pathname.split('/')[1];
    } else {
        var currentProfile = location.pathname.split('/')[3];
    };

    // Get the next/prev query element (if any)
    console.log('6: ');
    console.log(query);
    var prev = query.slice(query.indexOf(currentProfile)-1)[0];
    var next = query.slice(query.indexOf(currentProfile)+1)[0];

    // Check if next/prev is undefined and if so, set to first/last element in query array
    if(prev){
        var prevProfile = prev;
    } else {
        var prevProfile = query.pop();
    };

    if(next){
        var nextProfile = next;
    } else {
        var nextProfile = query[0];
    };

    $scope.goToPrev = function() {
        // Check if user is on main site or portal
        if(location.pathname.split('/')[3] == null){
            var profileUrl = location.origin + '/' + prevProfile;
            // window.location = profileUrl;
            console.log(profileUrl);
        } else {
            var profileUrl = location.origin + '/' + location.pathname.split('/').slice(1,3).join('/') + '/' + prevProfile;
            // window.location = profileUrl;
            console.log(profileUrl);
        }
    };

    $scope.goToNext = function() {
        // Check if user is on main site or portal
        if(location.pathname.split('/')[3] == null){
            var profileUrl = location.origin + '/' + nextProfile;
            // window.location = profileUrl;
            console.log(profileUrl);
        } else {
            var profileUrl = location.origin + '/' + location.pathname.split('/').slice(1,3).join('/') + '/' + nextProfile;
            // window.location = profileUrl;
            console.log(profileUrl);
        }
    };
});

这是我更新的服务:     this.getQuery = function(){         返回新的Promise(function(){             var query = localStorage.getItem(' searchQuery');

        if(query == "" || query == [""] || query == null){
            var slugArray = [];
            return $http.get('/companies.json')
            .then(function(resp) {
                if(resp && resp.data) {
                    for(var i in resp.data) {
                        var result = resp.data[i];
                        if(resp.data[i].name){
                            slugArray.push(resp.data[i].name.toLowerCase().split(' ').join('-'));
                        }
                    }
                    setQuery(slugArray);
                } else {
                    resetQuery();
                }
                return slugArray;
            }, function(err) {
                resetQuery();
            });
        } else {
            return query;
        };
    });
};

1 个答案:

答案 0 :(得分:1)

Angular承诺通过$q服务提供。有关详细信息,请参阅documentation

下面概述了在您的服务中实施$ q承诺的基本概要,我将详细介绍如何保存到本地存储等:

this.getQuery = function(){
    var deferred = $q.defer();
    var query = localStorage.getItem('searchQuery');

    if(query == "" || query == [""] || query == null){
        $http.get('yoururl').then(function(resp) {
            // assuming resp is an array, else do your parsing to get array
            query = resp;
            deferred.resolve(query);
        }, function(err) {
            query = null;
            deferred.reject(err);
        });
    } else {
        deferred.resolve(query);
    };
    return deferred.promise;
};

然后您可以在控制器中使用它,如:

var query = null;
searchQuery.getQuery().then(function(result) {
    query = result;
}, function(err) {
    // Error occured
});