AngularJS: Waiting for an asynchronous call

前端 未结 3 1511
清歌不尽
清歌不尽 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:00

    Try

    var packingProvider = angular.module('packingProvider',[]);
    
    packingProvider.provider('packingProvider',function(){
        return{
           $get: function($http){
               return{
                  getPackings: function(){
                      return $http.post('../sys/core/fetchPacking.php').then(function(response){
                          return response.data; // packings
                      });
                  }
               }
           }
       }
    });
    

    Then

    packingProvider.getPackings().then(function(packings){
        console.log(packings);
    });
    

    Main idea: you need to return the promise object from the getPackings function. Not sure if you can make the call to it synchronous but it's almost definitely not a great idea to do so. Also, if you want to make "packings" a model object on your controller and use for a two-directional binding, you can safely assign the promise object, which Angular will resolve as soon as data comes through:

    $scope.packings = packingProvider.getPackings();
    

    UPDATE

    As of 1.2.0-rc.3 promise unwrapping has been deprecated (https://github.com/angular/angular.js/blob/master/CHANGELOG.md#120-rc3-ferocious-twitch-2013-10-14) , so the line of code above will not result in a two-directional binding any more.

提交回复
热议问题