簡體   English   中英

angular js在上下文中加載初始數據

[英]angular js to load initial data in context

我應該在哪里在angularjs應用程序中加載基本數據。 我已經創建了工廠初始名稱,我想將數據加載到服務中,以便每當我需要數據時,我都將使用我的服務而不是回服務器。

提示:我的問題是我正在將ng-controller應用於不同的div,因此創建了許多實例,我不想為每個實例從服務器加載數據。

app.factory('feedbackFactory', function ($http) {
   //factory code
});


app.factory('feedbackService', function ($http) {
   //service code
});


app.controller('feedbackController', function ($scope, feedbackService,feedbackFactory $filter) {
      // Constructor for this controller
init();

function init() {
   feedbackFactory.get(1234, 1, 20).then(function(data)
     {
        $scope.feedbackItems=data;
        // here load data into service
        });
    }
});

如果您的服務器支持緩存,則$http將默認使用E標簽,並且實際上僅從服務器取回一次數據(假設它沒有更新並且e標簽發生了變化)。 這將導致它命中服務器,但是得到304響應。

如果您想強制應用程序只與服務器對話一次,則需要設置某種變量,該變量將被檢查以查看它是否應該到達服務器...

app.factory('feedbackFactory', function ($http) {
    var checkServer = true;
    var results = [];
    function getStuff(x, y, z) {
        if (checkServer) {
            checkServer = false; // we don't want to check again! Maybe have a refresh button that sets this back to true?
            // do http call...
            $http.get("path").then(function(response) {
                // Here is the magic... use angular.copy to keep your results object the same but update its values!
                angular.copy(response, results);
            });
        }
        return results; // this will be updated by our inital call to the server!
    });
});

那可能不是所有有效的代碼,因為我只是在腦海中打了個打字,但是它應該使您足夠接近。 大的綁定到results對象,並使用angular.copy(httpResponseData, results)填充數據,如果您想在promise中綁定到調用本身,則可能要返回$q.when(results)直接綁定到feedbackFactory.results ;

app.factory('feedbackFactory', function ($http, $q) {
    var checkServer = true;
    var results = [];
    function getStuff(x, y, z) {
        if (checkServer) {
            checkServer = false; // we don't want to check again! Maybe have a refresh button that sets this back to true?
            // do http call...
            return $http.get("path").then(function(response) {
                // Here is the magic... use angular.copy to keep your results object the same but update its values!
                angular.copy(response, results);
                return results; // If you want to bind to the promise instead of .results directly
            });
        }
        return $q.when(results); // If you want to bind to the promise instead of .results directly
    });
});

您可以使用$ http緩存,因此第一次后將不會從服務器獲取數據。 請參閱此答案以了解如何在$ http中使用緩存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM