当我加载AngularJS文件时,我的代码在中的代码完全执行之前。然后函数完成其执行。如何暂停代码,直到.then函数中的代码执行。我的意思是我想进行同步ajax调用,我曾经在jQuery中使用async: false
。我想知道如何在angularJS中做到这一点。
预先感谢
下面是我的AngularJS
代码
var app = angular.module('myApp', [ ]);
app.controller("Ctrl",Ctrl);
function Ctrl($http){
var self=this
ajaxCall();
function ajaxCall(){
return $http.get('/getData/')
.then(function(data){
// this below alert should come before the last alert
alert(" should execute first then below alert")
self.data=data
})
}
alert("getting executed first")
}
答案 0 :(得分:0)
您的ajaxCall()
返回promise
。这样您就可以等到完成为止。
$ http API基于$ q服务公开的延迟/承诺API。对于简单的使用模式而言,这并不重要,对于高级使用而言,熟悉这些API及其提供的保证很重要。
var app = angular.module('myApp', [ ]);
app.controller("Ctrl",Ctrl);
function Ctrl($http){
var self = this;
function ajaxCall(){
return $http.get('/getData/')
.then(function(data) {
// this below alert should come before the last alert
alert(" should execute first then below alert")
self.data = data;
}
);
}
// You can use .then here, because ajaxCall returns a promise
ajaxCall().then(function () {
alert("getting executed first");
})
}
答案 1 :(得分:0)
如果您连锁承诺会怎样?
function Ctrl($http, $q){
var self = this;
ajaxCall();
function ajaxCall(){
return $http.get('/getData/')
.then(storeData)
.then(proceed);
}
function storeData(response) {
alert("1st");
self.data = response.data;
return $q.when(self.data);
}
function proceed(data) {
alert("2nd");
}
}