Reputation: 829
I'm getting the data in services but I have received the data as Undefined. My AngularJS Service returns the data but I received as Undefined.
My Service code:
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;
});
};
});
My Controller Code:
myApp.controller("studentcontroller", function ($scope, $http, studentinfo) {
$scope.StudentList = [];
function LoadStudentRecord(){
$scope.StudentList = studentinfo.GetStudentList();
}
LoadStudentRecord();
});
Upvotes: 0
Views: 42
Reputation: 3426
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();
});
The service should looks something like that. You use the promise in your controller.
Upvotes: 1
Reputation: 5401
You are mixing a couple of things up here, as mentioned:
$.getJSON
)- where I recommend you try to stay with the Angular $http
( which you are injecting by the way ). So try to use $http.GET ( https://docs.angularjs.org/api/ng/service/$http ).Code:
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();
}]);
Upvotes: 4
Reputation: 3426
I see you inject $http but you don't use it. Replace the jQuery method with $http. $http will return a promise and the in the controller you can update your model with any of the promise method (then, catch, finally)
Upvotes: 3