[英]How can I process the response from $http, return a promise and bind to the result in AngularJS?
[英]how can I parse this result in angularjs promise
我有這樣的服務
app.service('newsService', function($q, $timeout,$http) {
this.getNewsName = function(id) {
var deferred = $q.defer();
var newsId = parseInt(id, 10);
$timeout(function() {
$http({
url: "entry/GetNewsTitle",
method: "POST",
data: $.param({'id':newsId}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data, status, headers, config) {
deferred.resolve(data.name);
})
.error(function(data, status, headers, config) {
console.log('failed');
});
}, 10);
return deferred.promise;
}
另一個函數中的console.log(deferred.promise)
給了我三個函數“catch”“finally”和“then”但是如何再次實現data.name
呢?
像這樣:
newsService.getNewsName(id).then(function(name) {
});
首先,您應該優化服務方法以避免延遲反模式 。 您不需要創建虛擬延遲對象,因為$http(...)
已經返回Promise。
該服務將如下所示:
app.service('newsService', function($http) {
this.getNewsName = function(id) {
return $http({
url: "entry/GetNewsTitle",
method: "POST",
data: $.param({
'id': parseInt(id, 10)
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
return data.name;
}).error(function(data, status, headers, config) {
console.log('failed');
});
};
});
注意, getNewsName
返回$http
結果。
使用此服務的控制器將使用Promise API鏈接到它:
newsService.getNewsName(123).then(function(name) {
console.log(name);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.