[英]$http get return a promise angular
我在服務中有此代碼,它對我有用。 據我所知, $http.get()
返回一個promise,promise異步執行,所以為什么我需要使用deffered.resolve(res.data)
返回服務中的數據。 非常感謝。
data.posts = function(page, perPage, format, orderBy) {
var deffered = $q.defer();
$http.get(hostName, {
params: {
'page': page,
'per_page': perPage,
'filter[post_format]=': format,
'filter[orderby]=': orderBy,
'order': 'desc'
}
}).then(function(res) {
deffered.resolve(res.data);
})
return deffered.promise;
}
如果確實在服務中,則不需要推遲。 服務中的方法從上述$ http請求中返回promise。
function exampleService($http) {
var data = this;
data.post = function(page, perPage, format, orderBy) {
return $http.get(hostName, {
params: {
'page': page,
'per_page': perPage,
'filter[post_format]=': format,
'filter[orderby]=': orderBy,
'order': 'desc'
}
}).then(function(res) {
//do stuff with success
})
.catch(function(err) {
//do stuff with error
})
.finally(function() {
//optionally use this as well maybe if you had loading type overlay/icon
});
};
}
//preferred method as it makes methods available before the sevice has been returned
function exampleService($http) {
function post(page, perPage, format, orderBy) {
return $http.get(hostName, {
params: {
'page': page,
'per_page': perPage,
'filter[post_format]=': format,
'filter[orderby]=': orderBy,
'order': 'desc'
}
}).then(function(res) {
//do stuff with success
})
.catch(function(err) {
//do stuff with error
})
.finally(function() {
//optionally use this as well maybe if you had loading type overlay/icon
});
}
//revealing module pattern
return {
post: post,
};
}
為什么要使用它? 因為作者並不了解。 但是,有很多原因不使用它 。
該代碼應閱讀
data.posts = function(page, perPage, format, orderBy) {
return $http.get(hostName, {
params: {
'page': page,
'per_page': perPage,
'filter[post_format]=': format,
'filter[orderby]=': orderBy,
'order': 'desc'
}
}).then(function(res) {
return res.data;
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.