問題:

當我使用 $http 服務從遠程API獲取數據時,下面的代碼片段無法將數據返回到控制器。
myApp.factory("myFactory", function ($http) {
var data = { anArray: [] };
$http.get("/api").success(function (response) {
data.anArray.push(response);
});
return data;
});
這個問題的出現是因為在 $http GET請求將數據推送到數組之前,就執行了 return 語句。
我的解決方案:
為了異步處理數據,當數據被接收到時,控制器需要指導服務採取什麼行動:
myApp.factory("myFactory", function ($http) {
return {
getData: function () {
return $http.get("/api");
},
};
});
myApp.controller("MyController", [
"$scope",
"myFactory",
function ($scope, myFactory) {
$scope.data = [];
var handleSuccess = function (response, status) {
$scope.data = response;
};
myFactory.getData().success(handleSuccess);
},
]);
如果你有任何問題,請讓我知道。😊