[英]AngularJS $http result with promise
我是angular $ q服務的新手,我將$http
和angular $q
服務一起使用來實現異步請求。 以下是我的代碼,無法獲取后端api的結果。 (JSON)
Services.js :
.service('httpService', function($q, $http, $timeout) {
var asyncRequest = function(url) {
return $http.get(url)
.then(function(response) {
//res is the index of an array in php, which will be encoded.
return response.res;
}, function(response) {
// something went wrong
return $q.reject(response.res);
});
};
return {
asyncRequest : asyncRequest
};
});
Controller.js :
var result = httpService.test(url)
.then(function(data) {
// Line below gives me "undefined"
console.log(data);
}, function(error) {
alert("Error...!");
});
提到的那行,給我未定義。 (當然,我可以在main函數中編寫console.log(data),但這不是一個好習慣,因為我想將結果返回給controller )
關於$q
服務的實現,有沒有更簡單的方法?
任何想法將不勝感激。
你不應該使用$q
在這種情況下,如$http
已經返回一個承諾。 將2一起使用效率低下。 (如果您使用的是非角度異步功能,例如地理查詢,則可以使用$q
)。
Services.js:
.service('httpService', function($http, $timeout) {
var asyncRequest = function(url) {
return $http.get(url)
};
return {
asyncRequest : asyncRequest
};
});
Controller.js:
var result = httpService.asyncRequest(url)
.then(function(res) {
console.log(res.data);
}, function(error) {
alert("Error...!");
});
第一件事是您使用的是工廠樣式而不是服務。 服務只是在this
引用上定義方法的函數。
我認為您不需要使用.then
在服務中只需返回$ http返回的promise
app.service('httpService', function($q, $http, $timeout) {
this.asyncRequest = function(url) {
return $http.get(url);
};
});
並在控制器中
var result = httpService.test(url)
.then(function(res) {
// Line below gives me "undefined"
console.log(res.data);
}, function(error) {
alert("Error...!");
});
我認為您正在為工廠的服務使用語法。
.service('httpService', function($q, $http, $timeout) {
this.asyncRequest = function(url) {};
});
要么
.factory('httpService', function($q, $http, $timeout) {
return {asyncRequest: function(url) {}};
});
在上述行中,響應已被拒絕。 您不需要拒絕其他任何東西。 因此,您不需要$q
。
首先,您已經返回了承諾。 您可以在控制器中通過添加$http
promise的success()
和error()
委托來處理它。 其次,這是異步操作。 而且您無法從jQuery.ajax()
類的成功回調中返回響應。 這不是同步調用,這是異步調用,您必須使用回調。 您的錯誤在這里。 只需返回promise,並在響應已被解決或拒絕時在控制器中進行處理即可。
因此,您的控制器代碼可以像這樣:
httpService.asyncRequest({
...
}).success(function(successfulResponse) {
...
}).error(function(failedResponse) {
...
});
.service('httpService', function($q, $http, $timeout) {
var asyncRequest = function(url) {
var defer = $q.defer();
return $http.get(url)
.then(function(response) {
//res is the index of an array in php, which will be encoded.
defer.resolve(response);
}, function(response) {
// something went wrong
defer.reject(response.res);
});
return defer.promise;
};
return {
asyncRequest : asyncRequest
};
});
你應該像這樣從你的對象返回承諾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.