Reputation: 569
I am having simple Angularjs 1.7 app. Everything works fine and I am able to fetch data from web API to angularjs service. When I debug on Angularjs service I can see that data is being fetched from database via Web API. So I am using the service inside angularjs controller to fetch the data into scope object. But I am not sure why the data is not being fetched in controller scope object. Is there anything that I am missing to fix it.
Service.js
(function () {
var app = angular.module('myApp');
app.factory('websiteService', function ($http, $q) {
var factory = [];
var deferred = $q.defer();
var baseURI = 'http://localhost:59029/api';
factory.getAllStudents = function () {
$http({
method: 'GET',
url: baseURI + '/Website/GetAllStudents'
}).then(function (response) {
deferred.resolve(response);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
return factory;
});
})();
Controller.js
(function () {
var app = angular.module('myApp');
app.controller('websiteController', ['$scope', '$http', 'websiteService', '$filter',
function ($scope, $http, websiteService, $filter) {
$scope.TestWebsite = "TestWebsite";
console.log($scope.TestWebsite);
//GET Students
websiteService.getAllStudents()
.then(function (response) {
$scope.FetchedAllStudents = response;
// NOT ABLE TO FETCH THE DATA HERE
}, function (error) {
// error handling here
});
}
]);
})();
Upvotes: 1
Views: 731
Reputation: 48968
There is no need to manufacture a promise with $q.defer
as the $http service already returns a promise:
app.factory('websiteService', function ($http, $q) {
var factory = [];
̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
var baseURI = 'http://localhost:59029/api';
factory.getAllStudents = function () {
return $http({
method: 'GET',
url: baseURI + '/Website/GetAllStudents'
}).then(function (response) {
return response.data;
});
}
return factory;
});
For more information see Is this a "Deferred Antipattern"?
Upvotes: 1