我正在尝试从angular js的http请求返回一些数据,但是它给出了未定义的

时间:2019-09-18 07:24:13

标签: javascript php angularjs

这里是angular js的控制器,正在调用该服务以获取酒店

   vm.getTopHotels =  function(){
         var hotelsLimit =  10;
         var top_hotels = 
         dataService.getHotels()
          .then(function(hotels){
             console.log('adf');
              sortHotels = commonMethods.sortHotels(hotels.data.data,'Rating','SORT_DESC'); 
              hotelDetailsCheck = checkDetailsIfExists(sortHotels);
              //Get only top 10 hotels for home page
              top_hotels =  hotelDetailsCheck.slice(0,10);
              vm.topHotels =  top_hotels;
          },
          function(data){
              console.log('Failed to get Hotels');
          }); 
     };

     vm.getTopHotels();

**这是dataService,它正在调用Http get请求以获取数据,但是在控制器中,它给了我未定义的信息,所以datsService返回方法中出了点问题,因为我认为它没有返回** < / p>

(function(){  
    angular
       .module('app')
       .factory('dataService',DataFactory);

       DataFactory.$inject = ['$http','$q']

       function DataFactory($http,$q){
          var service = {
              hotels:[],
              getHotels:getHotels,
              saveHotels:saveHotels
          };
           return service;

          function saveHotels(){
            var def = $q.defer();
             $http.get('/hotels/saveHotelsData')
              .then(function successCallback(data){
                    def.resolve(data);
               },function errorCallback(data){
                  def.reject('Something went down :(');
               });
               return def.promise;
          }

         function getHotels(){
            // var def = $q.defer();

           return  $http.get('/hotels/getHotelsData')
               .then(function successCallback(data){
                   service.hotels = data;
                });


          }


       }

})();

1 个答案:

答案 0 :(得分:1)

// ...
.then(function(data) {
    console.log('adf');
    sortHotels = commonMethods.sortHotels(hotels.data.data,'Rating','SORT_DESC'); 

hotels是什么?它没有在任何地方声明。如果hotels应该是API的响应,则应这样声明:

.then(function(hotels) {
    console.log('adf');
    sortHotels = commonMethods.sortHotels(hotels.data.data,'Rating','SORT_DESC'); 

更新:您的getHotels通过不带return语句的函数传递结果,因此将解析为未定义。应该是

         function getHotels(){
           return  $http.get('/hotels/getHotelsData')
               .then(function successCallback(data) {
                   service.hotels = data;
                   return data;
                });
          }