AngularJS: Using Shared Service(with $resource) to share data between controllers, but how to define callback functions?

前端 未结 4 742
自闭症患者
自闭症患者 2020-12-11 04:45

Note: I also posted this question on the AngularJS mailing list here: https://groups.google.com/forum/#!topic/angular/UC8_pZsdn2U

Hi All,

I\'m building my fi

相关标签:
4条回答
  • 2020-12-11 04:57

    In this new scenario you could use a $scope.$watch. The way you use it is as follows.

    $scope.countries = CountryService.getCountries();
    
    $scope.$watch('countries',function(newValue){
    //need to check if newValue has a value because 
    //the first time watch fires it will be undefined.
        if(newValue && newValue.length > 0 ){
            $scope.selected.country = $scope.countries[0];
        }
    });
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-11 05:00

    You should take a look at the $q service, you can do:

    promise.then(callback);
    

    From 1.1.3, you can access promises with $then, for exemple resource.query().$then(callback);

    0 讨论(0)
  • 2020-12-11 05:03

    AngularJS has its own way of caching queries, which you should use. As for the callback, it's no use assigning the query to a variable, since a promise will be returned anyway. You should simply always expect a promise, and pass your callback inside success or finally.

    0 讨论(0)
  • 2020-12-11 05:16

    Ok..so looks like I solved the problem by passing a callback function all the way up to the resource.query() call. Still not sure if this is the best way to do this.

    For reference, this is what I did:

    CountryController:

    $scope.countries = CountryService.getCountries(function(){
        //preselected default
        $scope.selected.country = $scope.countries[0];  
    });
    

    CountryService:

    //Country Service. Will contain all relevant rest methods here
    services.factory('CountryService', function($resource) {
        var countryService = {};
    
        var data;
        var resource = $resource('http://localhost:port/restwrapper/country.json', {port: ':8080'});
    
        var countries = function(callback) {
            data = resource.query(callback);
            return data;
        }
    
    
        return {
            getCountries: function(callback) {
                if(data) {
                    console.log("returning cached data");
                    return data;
                } else {
                    console.log("getting countries from server");
                    return countries(callback); 
                }
    
            }
        };
      });
    
    0 讨论(0)
提交回复
热议问题