2017-08-15 101 views
2

我正在编写一个从php文件返回狗品种列表的工厂,但我无法将响应数据返回给我的控制器。我有这样一个工厂在HTTP请求之后将数据从工厂返回给控制器AngularJS

angular.module('myApp') 
    .factory('DataService, function($http) { 
     return { 
      get_breeds: function() { 
       method: 'GET', 
       url: 'http://localhost:8080/php/api/getbreeds.php' 
      }).then(function onSuccess(response) { 
       console.log(response); // responds with 200 
       return response.data; 
      }).catch(function onError(err) { 
       console.log(err); 
      }) 
     } 
    } 
}); 

,这是我的组件

angular.module('myApp') 
    .component('homeComponent', { 
    templateUrl: 'home.component.html, 
    controller: function (DataService) { 

     DataService.get_breeds() 
      .then(function(response) { 
       var dog_breeds = response; 
       console.log(dog_breeds) 
      }); 
    ... 

的一部分,但我没有收到任何返回和错误消息。有人能指引我朝着正确的方向吗?

+0

不确定你是否复制并粘贴错误,但是这行'templateUrl:'home.component .html,'缺少一个结束单引号 – user2340824

+0

啊啊,这是一个错误的C&P错误! –

+0

您是否想要在'getBreeds'中返回'Promise'?该功能看起来不正确,语法荧光笔也困惑。或者你在'getBreeds'中使用注入'$ http'的地方? – sabithpocker

回答

0

单从服务返回的HTTP请求

angular.module('myApp') 
    .factory('DataService, function($http) { 
     var service = this;  
     service.get_breeds = function() { 
      return $http.get('http://localhost:8080/php/api/getbreeds.php') 
     } 
    } 
}); 
+0

我发布后不久,我就明白了!最后我想出了这个: angular.module('myApp') –

1

我想通了没多久,我张贴的问题!

最后我做了一个工厂,只是从URL返回的数据:

angular.module('myApp') 
    .factory('DataService', function($http) { 
     return { 
      get_dog_breeds: function(urlString) { 
       return $http.get(urlString) 
     } 
    } 
}) 

然后把它称为我的组件的控制器,就像这样:

DataService.dog_breeds('http://localhost:8080/php/api/getbreeds.php') 
      .then(function (response) { 
       console.log(response.data); 
       $scope.dog_breeds = response.data; 
       return $scope.dog_breeds; 
      }).catch(function (error) { 
      console.log('Error returned: ' + error 
       + ' Please make sure the service you\'re trying to use exists'); 
      return false; 
     }); 

它只是工作!

爱AngularJS到目前为止,顺便说一句家伙:)

0

尝试这样做它应该工作

使用此贵厂

angular.module('myApp') 
.factory('DataService', function($http) { 
    return { 
     get_breeds: function() { 
      var request = $http({ 
      method: 'GET',        
      url: 'http://localhost:8080/php/api/getbreeds.php' 
     }); 
     return request; 
    } 
} 
}); 

,并使用该控制器中检索数据

DataService.get_breeds() 
    .then(function(response){ 
     console.log(response.data); 
});