[英]How to get an ajax result to a controller in Angular?
我有一項服務,可以從我的ajax調用中獲取價值。 我想將該值存儲在變量中,然后將該變量傳遞給控制器。
angular.module("Data", []).service("DataService", function($http) {
return {
Data: function(callback) {
$http.get('http://www.w3schools.com/angular/customers.php').success(callback);
}
}
})
angular.module("Home", ["Data"]).service("HomeService", function(DataService) {
var customerData = {}
return {
Getdata: DataService.getCustomers(function(results) {
customerData = results;
console.log(customerData)
})
}
})
angular.module("Home").controller("HomeCntrl", function($scope, HomeService) {
$scope.Result = HomeService.Getdata;
})
我希望將數據存儲在customerData
並且必須將customerData
傳遞給控制器。
您不應該為此使用回調(盡管這也是可能的),並不是很方便。 對於這種情況, 承諾就是一切。 因此,您的代碼實際上應該是這樣的:
angular.module("Data", []).service("DataService", function($http) {
return {
getCustomers: function() {
return $http.get('http://www.w3schools.com/angular/customers.php').then(function(response) {
return response.data;
});
}
}
});
angular.module("Home", ["Data"]).service("HomeService", function(DataService) {
return {
getData: function() {
return DataService.getCustomers().then(function(data) {
console.log('customers', data);
// maybe process data further and return new set
return data;
});
}
}
});
angular.module("Home").controller("HomeCntrl", function($scope, HomeService) {
HomeService.getData().then(function(data) {
$scope.Result = data;
});
});
請看我的例子:
https://github.com/AlexRepeckiy/todolist/tree/master/app
遵循服務和控制器文件夾。
小例子:
app.controller('MainCtrl', ['$scope', 'DataService', function($scope, DataService) {
DataService.getData().then(function (results) {
$scope.tasks = results;
});
}]);
app.factory('DataService', ['$http', '$q', function ($http, $q) {
var exports = {};
exports.getData = function () {
var deferred = $q.defer();
$http.get('/gettask')
.then(
function (result) {
deferred.resolve(result.data);
},
function (error) {
deferred.reject(error);
console.log('Getting is fail :' + error);
});
return deferred.promise;
};
return exports;
}]);
不延遲:
app.factory('DataService', ['$http', function ($http) {
var exports = {};
exports.getData = function () {
return $http.get('/gettask')
.then(
function (result) {
return result.data;
},
function (error) {
console.log('Getting is fail :' + error);
});
};
return exports;
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.