我在服务中获取数据但我收到的数据为 Undefined 。我的AngularJS服务返回数据但我收到未定义。
我的服务代码:
myApp.service("studentinfo", function ($http) {
var studentlist = [];
this.GetStudentList = function () {
$.getJSON("/Home/GetStudentsList", function (data) {
if (data.Result == "OK") {
studentlist = data.Data;
}
else {
studentlist = [];
}
}).complete(function() {
return studentlist;
});
};
});
我的控制器代码:
myApp.controller("studentcontroller", function ($scope, $http, studentinfo) {
$scope.StudentList = [];
function LoadStudentRecord(){
$scope.StudentList = studentinfo.GetStudentList();
}
LoadStudentRecord();
});
答案 0 :(得分:4)
如上所述,你在这里混合了几件事:
$.getJSON
) - 我建议您尝试使用Angular $http
(顺便注入它)。因此,请尝试使用$ http.GET(https://docs.angularjs.org/api/ng/service/ $ http)。代码:
var app = angular.module('myapp', []);
app.service('studentservice', ['$http', function ($http) {
getStudentList = function () {
return $http.get('/Home/GetStudentsList');
};
return {
getStudentList: getStudentList
}
}]);
app.controller('studentcontroller', ['$scope', 'studentservice', function ($scope, studentservice) {
$scope.StudentList = [];
function LoadStudentRecord() {
$scope.StudentList = studentservice.getStudentList()
.success(function (data, status, headers, config) {
$scope.StudentList = data;
})
.error(function (data, status, headers, config) {
console.log(data)
});
}
LoadStudentRecord();
}]);
答案 1 :(得分:3)
我看到你注入$ http但你没有使用它。用$ http替换jQuery方法。 $ http将返回一个promise并且在控制器中你可以使用任何promise方法更新你的模型(然后,catch,最后)
答案 2 :(得分:1)
function studentFunction ($http) {
var studentlist = [];
this.GetStudentList = function () {
return $http.get("/Home/GetStudentsList");
};
}
myApp.service("studentinfo", studentFunction);
myApp.controller("studentcontroller", function ($scope, studentinfo) {
$scope.StudentList = [];
function LoadStudentRecord(){
studentinfo.GetStudentList().then(function (respoonse) {
$scope.StudentList = respoonse;
});
}
LoadStudentRecord();
});
服务看起来应该是这样的。您可以在控制器中使用promise。