2015-09-07 32 views
2

我爲我的angularJS應用程序實施了一項小服務,該服務向我的服務器發送了一個http請求,用於發送幾個文本消息。這是我目前的執行:如何在http請求完成後從angularJS服務返回對象?

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; 
    } 
    } 
}]); 

這樣做的問題是,HTTP請求是不是由正在返回的posts陣列的時間完成。我的直覺告訴我要在http .then函數中放置返回函數,以便只在請求完成時才返回,但這是不允許的。

有什麼辦法可以延遲posts的回報,直到http請求完成?

回答

2

您向致電者返回承諾。這樣,來電者可以「聽」承諾。爲了僅返回posts,您必須附加一個then,其返回response.data.items。之後鏈接的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; 
    }); 
} 

這樣一來,調用者也可以從承諾附上then

postFetcher.getList().then(function(posts){ 
    // use `posts` (which is response.data.items) 
}); 

爲了只調用一次,你可以存儲在變量中的承諾。然後有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 
+0

尼斯,這是有道理的。但是,有沒有辦法將http請求保留在返回函數之外呢? –

+0

太棒了。最後一個問題,如果你不介意。將'$ http.get'存儲到'posts'中時,是否正在執行查詢?或者直到我在我的控制器中調用'getList()'纔會執行它? –

+0

@ByronS在工廠創建時執行。 – Joseph

3

使用promise這是一個方式,我看到:
廠:

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; 
}); 
相關問題