codes: 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 result:
TypeError: Cannot read property 'then' of undefined at new (ht.../www/js/controllers.js:42:33) at invoke (ht.../www/lib/ionic/js/ionic.bundle.js:11994:17)...
where is wrong in these codes?
You need to return deferred.promise
from the getMainMenuItems function instead of in the callback functions used for $http.jsonp
. This is because getMainMenuItems
needs to return a promise.
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;
}
}
}])
Another alternative is to instead just return the promise from $http.jsonp
:
return {
getMainMenuItems: function(){
return $http.jsonp(urlStr,{params: ptStr});
};
You should return the promise object outside the $http. You can also return the $http because is a promise, is not necessary to have another promise.
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;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With