0

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.

5
  • 1
    sendRequest doesn't return anything... You can return a promise and handle it in the controller. Commented Jan 27, 2016 at 3:56
  • @elclanrs do you mean like this, return $http({ method: 'GET', url: 'localhost:3000/json' }); Commented Jan 27, 2016 at 3:57
  • 1
    Yes, then in the controller do the .then and inside do $scope.content = Commented Jan 27, 2016 at 3:58
  • @elclanrs I tried that, it is working, but i want the service to gather the response and send it back to the caller (I didn't want to return promise for each and every call, then write success and error methods for each call). Is their any other way. Commented Jan 27, 2016 at 4:05
  • 1
    @user3278897 no, that's the way to work with async tasks, by now. You can take a look at async and await on ES7 but just for curiosity. Commented Jan 27, 2016 at 4:10

1 Answer 1

1

Your service should be look like this,

app.service('MyService', function($http) {
    this.sendRequest = function() {
        // You should return $http's result
        // $http will return a promise
        return $http({
          method: 'GET',
          url: 'http://localhost:3000/json'
        }).then(
            function successCallback(response) {
                console.dir('This is the response');
                console.dir(response);
                return response.data;
            }, function errorCallback(response) {
                console.dir('This is the error');
                console.dir(response);
                return response;
            }
        );
    };
    this.addition = function(a,b) {
        return a+b;
    }; 
});

Now modify your controller like this,

app.controller('myCtrl', function($scope, MyService) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    console.dir(MyService.addition(4,5));
    MyService.sendRequest().then(function success(data){
       // here you will get your server data
       var a = data;
    }, function error(){

    });
    console.dir("Main program " + a);
    $scope.content = a;
});
Sign up to request clarification or add additional context in comments.

3 Comments

It's worth pointing out that the errorCallback will result in a resolved (successful) promise. It should be return $q.reject(response)
@Abhilash then what is the need of callback functions two times, i mean, why you are using "then" two times, once in the service and other time near the caller. Cannot we just return the return $http({ method: 'GET', url: 'localhost:3000/json' }) and write the then function once. More over, as i said in the comment that i already tried this and working fine by taking the advice of the elclanrs.
@Phil is right. In your errorCallback you are converting a rejected promise to a fulfilled promise. In errorCallback you should either throw response; or return $q.reject(response).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.