AngularJS: Waiting for an asynchronous call

前端 未结 3 1508
清歌不尽
清歌不尽 2021-01-04 12:43

I can\'t wrap my head around AngularJS\' concept of promises.

I have a provider:

var packingProvider = angular.module(\'packingProvider\',[]);

packi         


        
3条回答
  •  走了就别回头了
    2021-01-04 13:03

    The return value from within your then method isn't returning when you think it is; it's returning later.

    In the statement var packings = packingProvider.getPackings(); the return value is undefined because the promise returned from $http is asynchronous. That means that the call to $http.post happens, does not complete, then your function returns. In JS functions that don't return anything return undefined. The post call completes later and executes return packings; which gets returned to nowhere.

    The getPackings method should probably return the promise from $http.post directly. That way any code that wants to use this method can call then on the promise directly and set the value the way it needs to. In a controller you could assign that promise directly to the $scope and use it in your view. Here's a nice post that explains that particular feature: http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/

    Incidentally, it looks like you've got a long-winded service declaration there; any reason not to shorten it to something like this?

    var module = angular.module('packing', []);
    
    module.service('packing', function($http) {
      return {
        getPackings: function() {
          return $http.post('../sys/core/fetchPacking.php');
        }
      };
    });
    

    I'm relatively new to AngularJS but I don't see any gain in all that typing. ( =

提交回复
热议问题