![](/img/trans.png)
[英]Build simple cache in Angularjs service for data provide from http request which return object reference
[英]How to return object from angularJS service AFTER http request is complete?
我正在為我的angularJS應用實現一個小型服務,該服務向服務器發出一個HTTP請求以獲取幾個文本信息。 這是我當前的實現:
app.factory("postFetcher", ['$http', function($http){
var posts;
$http.get('https://cdn.contentful.com/spaces/k2mwszledbge/entries?access_token=afa8ba8572bb0232644d94c80cfd4ae01314cd0589b98551147aab50f7134e30')
.then(function(response){
posts = response.data.items;
});
return {
getList: function(){
return posts;
}
}
}]);
這樣做的問題是,在返回posts
數組時,http請求尚未完成。 我的直覺告訴我將return函數放置在http .then
函數內.then
以便僅在請求完成后才返回它,但是這是不允許的。
有沒有辦法可以將posts
的返回延遲到http請求完成之前?
使用諾言是我看到的一種方式:
廠:
app.factory("postFetcher", ['$http', '$q', function($http, $q){
var posts;
return {
getList: getListFn
};
function getListFn(){
var defer=$q.defer();
$http.get('https://cdn.contentful.com/spaces/k2mwszledbge/entries?access_token=afa8ba8572bb0232644d94c80cfd4ae01314cd0589b98551147aab50f7134e30')
.then(function(response){
if(response && response.data && response.data.items){
posts = response.data.items;
defer.resolve(posts);
}
});
return defer.promise;
};
}]);
在控制器中使用:
postFetcher.getList().then(function(data){
//data processing;
});
您向呼叫者返回承諾。 這樣,呼叫者可以“聽”諾言。 為了只返回posts
,您必須附加一個then
返回response.data.items
。 then
被鏈接的then
解析該值。
getList: function(){
return $http.get(...).then(function(response){
// resolve just `response.data.items` to the next attached then which
// would be from the caller of getList
return response.data.items;
});
}
這樣,調用者還可以在promise中附加一個then
:
postFetcher.getList().then(function(posts){
// use `posts` (which is response.data.items)
});
為了只調用一次,您可以將promise存儲在變量中。 然后讓getList
返回該承諾。 then
附加到已解決的承諾應立即解決到已解決的值。
var posts = $http.get(...).then(function(response){
return response.data.items;
});
return {
getList: function(){
return posts;
}
}
// Call getList() the same way as above
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.