[英]how to create synchronous using $http in angular.js?
我是Java腳本的初學者,如果有人有想法請理解我如何使用$ http對象創建同步Ajax調用,我如何通過$ http進行Ajax調用
我的代碼如下-
var AjaxModule = angular.module('AjaxModule',[]);
AjaxModule.controller('AjaxController',function($scope,$http){
var path ="http://localhost/services_ajax/";
var serviceName = 'customers';
var response = $http.get(path+serviceName);
response.success(function(data){
$scope.list = data;
});
});
您不能使用$ http服務發出同步請求。 它在服務代碼中被硬編碼為異步的。 但是,您可以進行自己的同步服務。
var myApp = angular.module('myApp', []);
myApp.service('synchronousService', [function () {
var serviceMethod = function (url) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Your browser don't support XMLHttpRequest");
}
request.open('GET', url, false);
request.send(null);
if (request.status === 200) {
return request.responseText;
}
};
return serviceMethod;
}]);
myApp.controller('AppCtrl', function ($scope, synchronousService) {
var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22AAPL%22%29&env=store://datatables.org/alltableswithkeys";
alert(synchronousService(url));
});
這是正在工作的jsfiddle: http : //jsfiddle.net/zono/uL0e1j3e/18/
只是說同步請求是一個非常糟糕的主意。
您可以使用有角度的諾言概念。 承諾提供同步工具。 我通過演示示例向您展示
var app = angular.module(“ myApp”,[]);
app.controller(“ ctrl”,function($ scope,$ q,$ timeout){
var task1 = $q.defer();
task1.promice.then(function(value){
// write a code here for your task 1 success
} ,function(value){
// write a code here for your task 1 error
});
var task2 = $q.defer();
task2.promice.then(function(value){
// write a code here for your task 2 success
} ,function(value){
// write a code here for your task 2 error
});
$q.all([task1.prpmice,task2.promice])
.then(function(){
// write a code which is executed when both the task are completed
} ,function(){
// write a code which is executed when some of the task are rejected
});
}
上面的代碼將幫助您了解angular的promice概念
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.