如何在使用 angularjs 中的工厂在 GPS 检测器函数内部使用 $http.post 方法时获得回调响应

how to get callback response while use $http.post method inside of GPS detector function using factory in angularjs

I try to throw error modal window when the gps not enable. perhaps it's enabled then it will call servcie callback using $http.post method. But without gps function it's working and return promises fine. if use GPS method above the post method then i got some error like "Uncaught TypeError: Cannot read property 'then' of undefined" What's wrong with my code. Anyone can give me some idea..

服务工厂:

   .service('DataServiceFactory', function($http, $rootScope){         //dynamic $http JSON Data Passing service
            return{
                serviceDataReq : function(reqUrl, reqData){
                    cordova.plugins.diagnostic.isGpsLocationEnabled(function(enabled){
                        if(enabled == 1){
                            return $http.post(reqUrl, reqData);
                        }else{
                            $rootScope.ErrorMsg = "Please Turn On your GPS location..";
                            $('#ErrorModal').modal('show');
                        }
                    }, function(error){
                        $rootScope.ErrorMsg = "GPS location Error : "+error;
                        $('#ErrorModal').modal('show');
                    })
                }
            }
        })

在控制器中:

DataServiceFactory.serviceDataReq($rootScope.primaryLiveServiceApiUrl, angular.toJson($scope.LoginAuthReq)).then(function(response) {

}, function(error){

});

我现在没有 cordova 示例来测试您的代码,但看看它,我会说如果设备没有 gps 功能,您的服务方法不会返回承诺。

我会这样做:

.service('DataServiceFactory', function($q, $http, $rootScope){         //dynamic $http JSON Data Passing service
         return {
            serviceDataReq: function(reqUrl, reqData){
                var deferred = $q.defer();
                cordova.plugins.diagnostic.isGpsLocationEnabled(function(enabled){
                    if(enabled == 1){
                      deferred.resolve($http.post(reqUrl, reqData));
                    }else{
                      $rootScope.loaded = false;
                      $rootScope.ErrorMsg = "Please Turn On your GPS location..";
                      $('#ErrorModal').modal('show');
                      deferred.reject("Please Turn On your GPS location..");
                    }
                }, function(error){
                    $rootScope.ErrorMsg = "GPS location Error : "+error;
                    $('#ErrorModal').modal('show');
                    deferred.reject("GPS location Error : "+error);
                });
              return deferred.promise;
            }
          };
    })