Angularjs /离子类型错误:无法读取属性“,然后”未定义 [英] Angularjs/Ionic TypeError: Cannot read property 'then' of undefined
问题描述
codeS:
JS:
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;
});
});
运行结果是:
类型错误:无法读取属性,然后未定义
在新的(HT ... / WWW / JS / controllers.js:42:33)
在调用(HT ... / WWW / lib中/离子/ JS / ionic.bundle.js:11994:17)...
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)...
错在哪里这些codeS?
where is wrong in these codes?
推荐答案
您需要从getMainMenuItems函数,而不是在用于回调函数返回 deferred.promise
$ http.jsonp
。这是因为 getMainMenuItems
需要返回的承诺。
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;
}
}
}])
另一种方法是不是只返回自许 $ http.jsonp
:
return {
getMainMenuItems: function(){
return $http.jsonp(urlStr,{params: ptStr});
};
这篇关于Angularjs /离子类型错误:无法读取属性“,然后”未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!