2017-02-14 24 views
0

我在這裏有一個問題,只要我點擊組件內部的按鈕,我看到我正在進行$ http調用,而我沒有得到在控制檯中的響應,但在瀏覽器中,我看到了呼叫。

只有當我取消註釋$超時功能時纔會調用數據。

JS

var app = angular.module('myApp', []); 
app.controller('mainCtrl', [$scope, $http, $timeout, function($scope, $http, $timeout) { 

    $scope.navigate = function() { 
     $scope.getStats(); 
    } 

    $scope.getStats = function() { 
     //$timeout(function() { 
      $http 
       .get('/scripts/controllers/fda/appSvc.json') 
       .then(function (response) { 
        console.log(response.data); 
       }, function (error) { 
        console.log(error); 
       }) 
    //}, 0) 
    }; 

    $scope.detailedTableCtrl = { 
     navigate: $scope.navigate 
    } 

}]); 

app.component("myBox", { 
     bindings: { 
      'detailedTableCtrl': '=' 
     }, 
     controller: function($element) { 

     }, 
     controllerAs: 'myBox', 
     templateUrl: "/template", 
     transclude: true 
}) 

HTML

<div ng-app="myApp" ng-controller="mainCtrl"> 
     <my-box detailed-table-ctrl="detailedTableCtrl"></my-box> 
    </div><!--end app--> 

<!--mybox component--> 
    <button class="btn btn-default btn-sm" ng-click="myBox.detailedTableCtrl.navigate()"> 
       <span class="glyphicon glyphicon-chevron-left"></span> 
       <span>Back</span> 
      </button> 
+2

我沒有看到你注射'$ http' – Amy

+0

或與此有關'$ timeout'! –

+1

我忘了在這裏添加它的問題,但我注入$ http和$ timeout –

回答

0

由於@Amy指出,我沒有看到$ http服務注入。也請使用服務消費數據並在控制器中注入服務。您的控制器不應該擔心調用/使用數據。

<!-- Controller to get data from the Service or Factory (pay attention to service injection here) --> 
app.controller('mainCtrl', ['$scope', 'dataService', function($scope,dataService) { 

    dataService.getData().then(function(response) { 
      $scope.response = response.data; 
     }, function(error) { 
      $scope.error = error; 
      $scope.response = []; 
     }); 
}); 

<!-- Factory to handle your data from REST or JSON --> 
(function() { 
    "use strict"; 
    app.factory("dataService",['$http', function($http){ 

    function getData(){ 
     return $http.get('/scripts/controllers/fda/appSvc.json'); 
    } 
    return { 
     getData : getData 
    }; 
}]); 
})(); 
+0

我忘了在這裏添加它的問題,但我注入$ http和$超時。我面臨的問題是$ http請求。我在瀏覽器中得到了響應,但不調用'.then'函數。只有在'$ timeout'中換行時纔會調用它 –