[英]Angular $http call to synchronous
angular.module('sample').factory('Service',
function( $rootScope, $http, $location )
{
return {
loadInfo: function()
{
var _url = 'url';
$http.get( _url )
.success( function( data )
{
console.log(data);
})
.error( function( response )
{
error( response );
});
},
});
我不能在沒有得到這個結果的情況下調用任何其他服務,但是由於它在弱網絡中是異步的,因此它有時間加載該結果並最終導致錯誤。 我如何才能使此呼叫同步。 想法是其他所有服務都應等到加載后再進行。 在jquery ajax中,我們可以很容易地設置true或false。但是我無法以角度進行設置,我還引用了其他一些答案,但似乎沒有任何效果。
請建議
您可以利用有角度的承諾。 $ q服務上的文檔
angular.module('sample').factory('Service',
['$rootScope','$http','$location','$q',function( $rootScope, $http, $location,$q )
{
return {
loadInfo: function()
{
var _url = 'url';
var deferred = $q.defer();
$http.get( _url )
.success( function( data )
{
deferred.resolve(data);
console.log(data);
})
.error( function( response )
{
deferred.reject(data);
error( response );
});
},
});
在您的Controller中,它將如下所示:
Service.loadInfo.then(
function(data){
//Whatever you want to do with the data on success
}
,function(data){
//Whatever you want to do on error
}
);
編輯 ,
我添加了$ q服務以及一些解決方法和延遲。 請檢查更新后的答案。
如果您可以向我們提供更多代碼,那將非常有幫助
您在代碼中犯了一個非常簡單的錯誤
angular.module('sample').factory('Service',
function( $rootScope, $http, $location,$q )
{
return {
loadInfo: function()
{
var _url = 'url';
var deferred = $q.defer();
return $http.get( _url )
.success( function( data )
{
console.log(data);
deferred.resolve(data);
})
.error( function( response )
{
error( response );
deferred.reject(response);
});
},
});
編輯為了訪問'then',您需要返回一個諾言,該諾言是我使用$ q.defer()創建的,並返回deferred.resolve()。
Cannot read property 'then' of undefined
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.