Angular JS从服务和Http回调方法返回数据

Angular JS return data from service and Http callback Method

本文关键字:回调 方法 返回 数据 Http JS 服务 Angular      更新时间:2023-09-26

创建了一个 Angular JS 服务,该服务向服务器发送 JSON 数据请求。我能够在服务中正确接收数据,但无法将数据返回到控制器。请检查如下:

<!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>

对于加法函数,我能够正确获取数据(我的意思是,它返回 4+5 的总和),但来到"sendRequest"方法,它正在调用此方法中的$http调用并返回调用方"null/空"数据而无需等待$http方法。

问题是,"sendRequest"方法中的调用$http异步的(我的意思是,一旦从服务器获得响应,就会调用"then"),我想等待服务器响应并向调用者发送响应。

你的服务应该是这样的,

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;
    }; 
});

现在像这样修改你的控制器,

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;
});