Angularjs/Ionic TypeError:无法读取未定义的属性'then'

joh*_*Lau 7 javascript angularjs ionic

代码:js:

angular.module('starter.services', ['ngResource'])
.factory('GetMainMenu',['$http','$q','$cacheFactory',function($http,$q,$cacheFactory) {
            var methodStr = 'JSONP';
            var urlStr = 'http://localhost/bd/wp-admin/admin-ajax.php';
            var ptStr = {action:'bd_get_main_menus',callback:'JSON_CALLBACK'};

            return {
                getMainMenuItems: function(){
                    var deferred = $q.defer();

                  $http.jsonp(urlStr,{params: ptStr})
                        .success(function (data, status) {

                            deferred.resolve(data);

                            return deferred.promise;
                        })
                        .error(function (data, status) {

                            deferred.reject(data);

                            return deferred.promise;

                        });
                }
            }

        }])

angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope, $ionicModal, $timeout, $http,GetMainMenu) {
    GetMainMenu.getMainMenuItems().then(
      function(data){
        $scope.mainMenus = data;
      });
});
Run Code Online (Sandbox Code Playgroud)

运行结果:

TypeError:无法在调用时读取未定义的属性'then'(ht .../www/js/controllers.js:42:33)(ht .../www/lib/ionic/js/ionic.bundle. JS:11994:17)...

这些代码哪里错了?

Way*_*ery 9

您需要deferred.promise从getMainMenuItems函数而不是在用于的回调函数中返回$http.jsonp.这是因为getMainMenuItems需要返回一个承诺.

angular.module('starter.services', ['ngResource'])
.factory('GetMainMenu',['$http','$q','$cacheFactory',function($http,$q,$cacheFactory) {
    var methodStr = 'JSONP';
    var urlStr = 'http://localhost/bd/wp-admin/admin-ajax.php';
    var ptStr = {action:'bd_get_main_menus',callback:'JSON_CALLBACK'};

    return {
        getMainMenuItems: function(){
            var deferred = $q.defer();

          $http.jsonp(urlStr,{params: ptStr})
                .success(function (data, status) {

                    deferred.resolve(data);
                })
                .error(function (data, status) {

                    deferred.reject(data);
                });

           return deferred.promise;
        }
    }
}])
Run Code Online (Sandbox Code Playgroud)

另一种选择是从$http.jsonp以下方面返回承诺:

return {
        getMainMenuItems: function(){
           return $http.jsonp(urlStr,{params: ptStr});
        };
Run Code Online (Sandbox Code Playgroud)