Angular - http.get returning undefined

前端 未结 1 1282
情深已故
情深已故 2021-01-28 18:26

I\'ve created a Factory to retrieve customers:

customerModule.factory(\"CustomerFactory\", [\"$http\", \"DataService\", function ($http, dataService) {

    var          


        
相关标签:
1条回答
  • 2021-01-28 18:57

    If you take a close look at your queryFn function you will notice that you're not actually returning anything from it. This means that queryFn will return undefined.

    So the first step to fixing your code is to put return in front of $http.

    Second step is fixing the way you are calling customerFactory.query function. You expect it to return the value immediately, but $http actually creates an XHR request, and XHR requests are async by default, so you cannot expect customerFactory.query to return the result right away.

    If you haven't learned of promises than this is the time to take a look at them, because they are used all over the place, in angular world.

    Assuming that you have put return in front of $http, the call to customerFactory.query will actually return a promise object. That promise object has a .then method. This method should be used as:

    customerFactory.query($scope.query)
      .then(function(customers){
        console.log(customers);
      });
    
    0 讨论(0)
提交回复
热议问题