不理解angularjs中的承诺

时间:2015-07-24 19:24:22

标签: javascript angularjs rest angular-promise

我认为我在使用AngularJS& REST,直到我遇到一个问题,我的数据服务没有及时返回数据,以便我的模型使用它。

所以,我已经查看并实现了一个promise,但是在HTTP REST调用完成之前它仍然没有延迟。

我很感激开明的任何帮助。

我的路由将预订ID传递给bookingController,后者会检索预订详情,然后在booking.html模板中以可编辑的形式显示。

testLabApp.controller('bookingController', function ($q, $scope, $location, $window, $routeParams, service) {
if ($routeParams.id) {
    $scope.bId = $routeParams.id;

    //Expected this to setup my promise
    var bookdefer = $q.defer();
    bookdefer.promise
        .then(function (booking) {

            //When successful the result is assigned to my booking in the controller $scope
            $scope.booking = booking;

            //I am making a copy for form updates
            $scope.editableBooking = angular.copy($scope.booking);

            //When it runs console displays error:-
            // "TypeError: Unable to get property 'Storeno' of undefined or null reference"
            console.log("[bookingCtrl] 1 New: " + $scope.booking.Storeno + " and Editable: " + $scope.editableBooking.Storeno);
        });

    // Is this not calling my getBooking service function with the Id passed into my controller?
    bookdefer.resolve(service.getBooking($scope.bookingId));

}
else {
    //...
}

当代码到达'[bookingCtrl] 1 ...'时,控制台显示错误“TypeError:无法获取未定义或空引用的属性'Storeno',这让我觉得预订数据还没有检索。

然后在此消息之后,控制台显示:

[getBooking] Done = Id: 209 | Store no: 9180 | Description: test | Status: Booked

我的数据服务包括许多进行REST调用的函数: -

testLabApp.factory('service', ['$rootScope', '$http', function ($rootScope, $http) {
    var service = {};

    $http({
        method: 'GET',
        url: "/_api/web/lists/GetByTitle('Bookings')/Items?$filter=Id eq '" + bookingId + "'",
        headers: {
            'Accept': 'application/json; odata=verbose'
        },
    }).success(function (d) {
        var e = d.d.results[0];
        booking = {
            Id: e['Id'],
            Storeno: e['Title'],
            BookedBy: e['BookedBy'],
            Description: e['Description'],
            StartDate: e['StartDate'],
            EndDate: e['EndDate'],
            Status: e['Status']
        };
        console.log("[getBooking] Done = Id: " + booking.Id + " | Store no: " + booking.Storeno + " | Description: " + booking.Description + " | Status: " + booking.Status);

        return booking;

    }).error(function (er) {
        console.log("[getBooking] http error : " + er);
    });
};

再次感谢任何帮助或建议。

此致 克雷格

2 个答案:

答案 0 :(得分:2)

服务中的成功函数是异步执行的。因此,您的服务实际上会向控制器返回null。这就是我在所有角度项目中所做的事情:

service.getStuff = function(id) {
    var dfd = $q.defer();

    $http({
        method: 'GET',
        url: '/api/some-end-point/id'
    }).then(function(data) {
        var result = data.data;
        dfd.resolve(result);
    }, function(error) {
        $log.error(error);
        dfd.reject(error);
    });
    return dfd.promise;
}

我的控制器写得像这样:

if ($routeParams.id) {
    $scope.bId = $routeParams.id;

    //Expected this to setup my promise
    service.getStuff($routeParams.id).then(
        function(data){
            $scope.booking = data;
        },
        function(error){
            console.log(error);
        }
    );
}

答案 1 :(得分:1)

'以下是来自使用服务的控制器的异步get调用的示例。您实际上可以将$ http.get()返回给控制器,以便不需要创建新的延迟对象:

(function(){

  angular.module('app', []);


  angular.module('app').factory('service', ['$http', function($http){

    return {
      getData: getData;
    }

    function getData(){
      return $http.get('/url')
        .success(function(data){
          //Do business logic here
          return data;
        })
        .error(function(error){
          return error;
        });
    }

  }]);

  angular.module('app').controller('controller', ['$scope', 'service',  function($scope, service){

    service.getData()
      .success(function(data){
        $scope.data = data;
      })
      .error(function(error){
        //error logic
      });
  }]);

})();