How do I prefetch url's in ionic/angularjs?

前端 未结 4 1649
渐次进展
渐次进展 2021-02-19 12:11

I am pretty new to ionic 1 and I am working on an application (with Ionic 1 and angular js) with multiple URLs where each URL brings up a list of categories, followed by a list

4条回答
  •  一向
    一向 (楼主)
    2021-02-19 13:00

    Best way to share data between different views in angular is to use a service as it is a singleton and can be used in other controllers. In your main controller you can prefetch your lists of categories asynchronously through a service which can be shared for next views.Below is a small demo which you refer

    angular.module("test").service("testservice",function('$http',$q){
        var lists = undefined;
        // fetch all lists in deferred technique
        this.getLists = function() {
          // if lists object is not defined then start the new process for fetch it
          if (!lists) {
            // create deferred object using $q
            var deferred = $q.defer();
             // get lists form backend
            $http.get(URL)
              .then(function(result) {
                // save fetched posts to the local variable
                lists = result.data;
                // resolve the deferred
                deferred.resolve(lists);
              }, function(error) {
                //handle error
                deferred.reject(error);
              });
            // set the posts object to be a promise until result comeback
            lists = deferred.promise;
          }
    
          // in any way wrap the lists object with $q.when which means:
          // local posts object could be:
          // a promise
          // a real lists data
          // both cases will be handled as promise because $q.when on real data will resolve it immediately
          return $q.when(lists);
        };
    this.getLists2=function(){
    //do it similarly as above
    };
    }).controller("mainController",function(testservice,$scope){
        $scope.lists1=testervice.getLists()
            .then(function(lists) {
            //do something 
            });
        };
        $scope.lists2=testervice.getLists2()
            .then(function(lists) {
            //do something 
            });
        };
        $scope.lists1();
        $scope.lists2();
    }).controller("demoController1",function(testservice,$scope){
        $scope.lists1=testervice.getLists()
            .then(function(lists) {
            //do something 
            });
        };
        $scope.lists2=testervice.getLists2()
            .then(function(lists) {
            //do something 
            });
        };
        $scope.lists1();
        $scope.lists2();
    });
    

提交回复
热议问题