TypeError:无法读取未定义的属性'then'#2
下面是我的角度应用程序。TypeError:无法读取未定义的属性'then'#2
(function() {
"use strict";
angular
.module("app.core", ['ngRoute'])
.controller("dataCtrl", dataCtrl);
dataCtrl.$inject = ['$scope','$location','dataService'];
/* @ngInject */
function dataCtrl($scope, $location, dataService) {
var methods = {
'Get': GetCustomers,
}
return methods.Get();
function GetCustomers(id) {
alert('test');
var scarData = dataService.read(id, "").then(function (data, err) {
console.log(data);
});
}
}
}());
服务
(function() {
'use strict';
angular
.module('app.service')
.factory('dataService', dataService);
dataService.$inject = ['$http', '$q'];
function dataService($http, $q) {
var service = {
create: create,
read: read,
update: update,
remove: remove
}
return service;
function read(id,type) {
return
$http.get("APIURL")
.then(success)
.catch(exception);
function success(response) {
}
function exception(ex) {
}
}
function create() {}
function update() {}
function detete() {}
}
})`
虽然调用来自控制器的服务我得到下面的错误。
TypeError: Cannot read property 'then' of undefined
此外,请在页面加载时建议更好的方式来调用控制器的get函数。
您的问题是由于Automatic Semicolon Insertion导致您的return语句比您预期的更早结束。
由于ASI,这样的:
return
$http.get("APIURL")
.then(success)
.catch(exception);
,就好像它已经被写成评价:
return;
$http.get("APIURL")
.then(success)
.catch(exception);
通知你有一个空的回报,然后你的$ HTTP调用。因此,您的服务方法返回未定义,并且您的$ http调用从未实际发生。
的解决方案是不返回和$ HTTP
return $http.get("APIURL")
.then(success)
.catch(exception);
是的,你是对的。谢谢 –
但现在在响应中,'我得到错误未捕获SyntaxError:意外的令牌:' –
请注意,因为它是CORS的请求,我需要使用jsonp而不是得到 –
移动'success'和返回语句之前'exception'功能之间添加一个换行符。 – Hoyen