代码: 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;
});
});
运行结果:
TypeError:无法读取属性'然后'未定义的 在新的(ht ... / www / js / controllers.js:42:33) 在调用(ht ... / www / lib / ionic / js / ionic.bundle.js:11994:17)......
这些代码中哪里错了?
答案 0 :(得分:9)
您需要从getMainMenuItems函数返回deferred.promise
,而不是在$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;
}
}
}])
另一种选择是从$http.jsonp
:
return {
getMainMenuItems: function(){
return $http.jsonp(urlStr,{params: ptStr});
};
答案 1 :(得分:4)
您应该在$ http之外返回promise对象。 你也可以返回$ http,因为这是一个承诺,没有必要有另一个承诺。
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
}
}
}])
angular.module('starter.controllers', [])
.controller('AppCtrl', function ($scope, $ionicModal, $timeout, $http, GetMainMenu) {
GetMainMenu.getMainMenuItems().then(
function (data) {
$scope.mainMenus = data;
});
});