在调用服务时检索控制器中的值,并将从服务接收的值返回给控制器

时间:2016-06-15 11:25:24

标签: javascript angularjs node.js angular-services angular-controller

Controller.js

在contoller.js中我有$ scope.data.state,当服务成功时它应该返回状态为$ scope.data.state,但是当我尝试在服务结束时在控制器中放置警报时得到与自己相同的状态而不是预订。我检查了我用于执行操作的WEBAPI,并且我获得了预订的成功。我只是想知道如何返回一个值。 非常感谢帮助。

$scope.data = {};
$scope.data.state = 'self';
$scope.data.starttime = new Date(new Date().getTime()).toLocaleTimeString();
$scope.data.endtime = new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleTimeString();


myPopup = $ionicPopup.confirm({

    template: ' Enter Start Time <input type="time" id="exampleInput" name="input" ng-model="example.value" placeholder="HH:mm:ss" min="08:00:00" max="23:00:00" required /> <br> Enter End Time <input type="time" id="exampleInput1" name="input1" ng-model="example1.value" placeholder="HH:mm:ss" min="08:00:00" max="23:00:00" required /> ',
    title: 'WS' + settings.label,
    scope: $scope
});


//alert(time1);
NotifyingCache.put('SeatId', settings.label);
NotifyingCache.put('starttime', $scope.data.starttime);
NotifyingCache.put('endtime', $scope.data.endtime);

myPopup.then(function (res) {
    if (res) {
        NotifyingCache.put('starttime',document.getElementById("exampleInput").value);
        NotifyingCache.put('endtime',document.getElementById("exampleInput1").value);

        //alert(time1);
        var booking = {};
        var stat = '';
        booking.SeatId = NotifyingCache.get('SeatId');
        booking.UserId = NotifyingCache.get('UserId');
        booking.StartDate = new Date().toISOString().slice(0, 10);
        booking.EndDate = new Date().toISOString().slice(0, 10);
        booking.StartTime = NotifyingCache.get('starttime');
        booking.EndTime = NotifyingCache.get('endtime');
        BookingService.bookinguser(JSON.stringify(booking)).success(function (data) {
            var infoPopup = $ionicPopup.alert({
                title: 'Success',
                template: 'The desk has been successfully booked for you.'
            });
            $scope.data.state = 'booked';

        }).error(function (data) {

            var alertPopup = $ionicPopup.alert({
                title: 'Booking Failed!!!',
                template: data.Message
            });
            $scope.data.state = 'self';

        });
    } 

Services.js

ServiceModule.service('BookingService', function ($q, $http){

     return{

    bookinguser: function(user){

    //  alert(user);
            var config = {
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                }
            }
            var deferred = $q.defer();
            var promise = deferred.promise;
            return $http.post('webAPI', user, config)
             .success(function (data, status, headers, config) {
                 deferred.resolve(data);
                 //return data;
             })
             .error(function (data, status, header, config) {
                 //alert(JSON.stringify(data));
                 var data =  "Data: " + data +
                     "<hr />status: " + status +
                     "<hr />headers: " + header +
                     "<hr />config: " + config;
                     deferred.reject(data);
             });
             promise.success = function (fn) {
                promise.then(fn);
                return promise;
            }
            promise.error = function (fn) {
                promise.then(null, fn);
                return promise;
            }
            return promise;
        }
    }
   });

1 个答案:

答案 0 :(得分:0)

我会尝试使用simil重构而不尝试代码。当你尝试它时,可能会发现一些拼写错误或错误。

让我们从服务开始

ServiceModule.service('BookingService', function ($q, $http){

     return {
              bookinguser: bookinguser
            }

    function bookinguser(user){
      var config = {
          headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                    }
          }

          return $http.get('/api/maa')
                      .then(bookinguserComplete)
                      .catch(bookinguserFailed);


          function bookinguserComplete(response) {
              return response.data.results;
          }

          function bookinguserFailed(error) {
              var data =  "Data: " + data +
                "<hr />status: " + status +
                "<hr />headers: " + header +
                "<hr />config: " + config;
              logger.error(data);
          }
    }
});

因此我在评论中告诉你http已经返回promise,所以你可以直接从$ http.post返回

正如您在服务中看到的那样,已有一个then和catch方法可以预先详细说明您的数据,但您仍然会返回一个承诺,因此您必须在控制器中解决它

现在是控制器

.
.
.

booking.EndDate = new Date().toISOString().slice(0, 10);
booking.StartTime = NotifyingCache.get('starttime');
booking.EndTime = NotifyingCache.get('endtime');

BookingService.bookinguser(JSON.stringify(booking)).then(function (data) {
  var infoPopup = $ionicPopup.alert({
        title: 'Success',
        template: 'The desk has been successfully booked for you.'
    });
    $scope.data.state = 'booked';
  }).catch(function (data) {
    var alertPopup = $ionicPopup.alert({
        title: 'Booking Failed!!!',
        template: data.Message
    });
    $scope.data.state = 'self';

  });

现在我真的不知道你的控制器做了什么,但尝试使用这种结构并告诉我发生了什么,所以我可以尝试帮助你更多。

P.S。 dataservice的重构不是我的想法,而是直接来自this angular styleguide