Вопрос

I have setup an AngularJS resource:

app.factory('gridData', function($resource) {
        var csrf = 'asdf';
        return $resource('/my/url/:expID', {expID:'@id'},{
                get: {method:'GET'},
                query: {method:'GET', isArray:true},
                save:{method:'POST', headers: {'X-CSRFToken' : csrf }}
          });
});

I'm injecting the gridData resource into my controller and using it to fetch data from the server:

       gridData.query(function(result) {
            console.log("result is");
            console.log(result);
            $scope.data = result;
        });

This approach works fine using AngularJS 1.3. The console.log(result) statement prints the actual data received.

Now I tried to downgrade to AngularJS 1.2.11 and I'm having an issue since the console.log(result) prints out a promise, as shown in this picture. Consequently $scope.data is set to the promise, but I actually need $scope.data set only when the actual data is available.

This is because in some version between 1.3 and 1.2 promises have been introduced into Angular. Any idea how to handle this situation / correctly deal with promises?

Это было полезно?

Решение

Check out the section titled "The Promise API" in the docs on the $q service. You can also checkout this video on Angular promises.

The main method you need to know about is .then. Here's how you could refactor your code with this method:

gridData.query(function(promise) {
            promise.then(function (result) {
              console.log("result is");
              console.log(result);
              $scope.data = result;
            });
        });

This example could be cleaner, but it works for illustrative purposes. Hope that helps.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top