使用angularjs中的http数据共享服务

时间:2015-03-11 20:43:49

标签: angularjs http

我不想在控制器上进行相同的http调用,所以我想创建一个获取数据并将数据返回给控制器的服务我试图这样做

控制器:

App.controller('SearchCtrl', function ($scope, $rootScope, $http, $location, ngDialog, Notification, validationSerivce, dataService) {
    $rootScope.pageName = '1-search';
    $scope.type = 'delivery';

    $scope.searchZip = function() {
        //vars
        var zip = $scope.zip;
        var type = $scope.type;

        //check empty zip
        if (typeof zip === "undefined" || zip === null){
            Notification.error({message: "no zipcode entered", delay: 3000});
        } else {
            //validate zip
            if (typeof validationSerivce.validateZip(zip) == "string") {
                Notification.error({message: validationSerivce.validateZip(zip), delay: 3000});
            } else {

                //set spinner and blur
                $scope.setBlur('add');
                $scope.setSpinner('show');

                //get the data
                console.log(dataService.getSearchData(zip,type));
            }
        }
    };
});

,服务看起来像这样:

App.factory("dataService", function($http) {
    return {
        getSearchData: function(zip,type) {
            //Get request
            $http({
                url: url+"/search?zip=" + zip + "&type=" + type,
                method: 'GET',
                headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
            }).success(function(data){
                return data;
            }).error(function(err){"ERR", console.log(err)});
        }
    };
});

但回报是'未定义'

api返回数据....我怎么能以最好的方式做到这一点?

2 个答案:

答案 0 :(得分:5)

getSearchData()函数中没有return语句。从$ http返回结果并将其作为承诺访问。 e.g。

dataService.getSearchData(zip,type).then(function(response) {
  console.log(response)
});

答案 1 :(得分:1)

试试这个:

App.factory("dataService", function($http) {
return {
    getSearchData: function(zip,type) {
        //Get request
        return $http({
            url: url+"/search?zip=" + zip + "&type=" + type,
            method: 'GET',
            headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
        }).success(function(data){
            return data;
        }).error(function(err){"ERR", console.log(err)});
    }
};
});