繁体   English   中英

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

[英]Angular JS return data from service and Http callback Method

创建了一个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调用并返回到调用方“空/空”数据,而无需等待$ 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;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM