Created a Angular JS service, which sends request to the server for the JSON data. I am able to receive the data correctly in the service, but i am unable to return data to the controller. Please check as follows:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
<br><br><br><br><br><br><br><br><br>
<p>The content is {{content}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.service('MyService', function($http) {
this.sendRequest = function() {
$http({
method: 'GET',
url: 'http://localhost:3000/json'
}).then(
function successCallback(response) {
console.dir('This is the response');
console.dir(response);
return response;
}, function errorCallback(response) {
console.dir('This is the error');
console.dir(response);
return response;
}
);
};
this.addition = function(a,b) {
return a+b;
};
});
app.controller('myCtrl', function($scope, MyService) {
$scope.firstName = "John";
$scope.lastName = "Doe";
console.dir(MyService.addition(4,5));
var a = MyService.sendRequest();
console.dir("Main program " + a);
$scope.content = a;
});
</script>
</body>
</html>
For the addition function, i am able to get data correctly (I mean, it is returning sum of 4+5), but coming to the "sendRequest" method, it is invoking the $http call in this method and getting back to the caller "null/empty" data without waiting for the $http method.
Problem is, $http call in the "sendRequest" method is asynchronous (I mean, "then" is called once it is getting the response from the server) and i want to wait for the server response and send response to the caller.
sendRequestdoesn't return anything... You can return a promise and handle it in the controller..thenand inside do$scope.content =