![](/img/trans.png)
[英]Error "TypeError: Cannot read property 'email' of undefined" using AngularJS and Ionic
[英]Angularjs/Ionic TypeError: Cannot read property 'then' of undefined
代码: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:无法在调用时读取未定义的属性'then'(ht ... / www / js / controllers.js:42:33)(ht ... / www / lib / ionic / js / ionic.bundle。 JS:11994:17)...
这些代码哪里错了?
您需要从getMainMenuItems函数而不是在用于$http.jsonp
的回调函数中返回deferred.promise
。 这是因为getMainMenuItems
需要返回一个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});
};
你应该在$ 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;
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.