2014-12-04 66 views
0

我知道数据来自服务器(我有单元测试,并看到调试器中的数据在铬)但我不知道如何将角度服务的数据返回角度控制器。如何从角度js中的服务返回值?

服务:

修订

surchargeIndex.service('customerService', [ 
'$http', function ($http) { 
    this.getTest = function() { 
     return $http({ 
       method: "GET", 
       url: "api/Customer/GetTest", 
      }) 
      .success(function(data) { 
       return data; 
      }); 
    }; 
} 

]);

控制器:

surchargeIndex.controller('SurchargeIndexController', function ($scope, customerService, templateService) { 
    $scope.customers = customerService.getTest(); 

}); 

的数据具有从该服务器阵列,使得所述阵列被在服务填充。所以重申数据在那里;但是,在调试期间,我收到成功处理程序的内部错误404。

我错过了什么?

回答

3

$http异步工作;幸运的是,它返回一个承诺,当从服务器检索到响应时,它将被履行。所以你应该返回$ http的get方法并使用返回的promise来处理数据。

this.getTest = function() { 
     return $http({ 
       method: "GET", 
       url: "api/Customer/GetTest", 
      }) 
      .success(function(data) { 
       return data; 
      }) 
      .error(function() { 
       alert("failed"); 
     }); // This returns a promise 

    }; 

然后在您的控制器中,您应该使用该承诺来检索预期数据。

surchargeIndex.controller('SurchargeIndexController', function ($scope, customerService, templateService) { 
    //Use the returned promise to handle data, first parameter of the promise is used for successful result, if error happens, second parameter of the promise returns the error and you can do your error handling in that function 
    customerService.getTest().then(function(customers){$scope.customers = customers;}, function(err){console.error(err);}) 
}); 
+0

你说它返回一个“承诺”,这是什么意思? – Robert 2014-12-04 15:06:01

+1

正如你可能知道JavaScript是异步工作的,所以当你通过'$ http'发出请求时,进程不会停止,直到它返回一个结果,但它会继续执行下一个命令。通过返回一个承诺,你给调用者一个钩子。当从服务器检索到一个响应时,Promise将被执行,客户端将通过promise的'then'函数被通知。您可能想要查看https://github.com/kriskowal/q这是广泛使用的承诺实现之一。 – cubbuk 2014-12-04 15:10:24

+0

好的,数据有数组,但不返回给控制器。我得到了一个成功处理程序,但是当我调试它时,我在成功处理程序中返回了一个404数据返回数据。 – Robert 2014-12-04 15:19:37

0

您需要定义一个回调,让您的数据“回”到你的控制器,一个异步HTTP调用后...有不同的方法去做......我会告诉你一个办法,而不回调或承诺,但最好的方法是使用一个回调,或承诺...

狂野西部方式:

app.controller('myCTRL', function($scope, myService) { 

     $scope.valueWanted = myService.valueWanted; 
     myService.getData(); 

}); 

app.service('myService', function($http) { 

     var myThis = this; 

     this.valueWanted = ""; 
     this.getData = function() { 
       $http.get('api/Customer/GetTest').success(function (data) { 
        myThis.valueWanted = data.valueWanted; 
       }); 
     }; 

});