2016-03-03 141 views
0

我有一個服務來從作爲參數傳遞的url中獲取數據。有用。 但是當我想通過這個數據到控制器$範圍,我沒有得到任何將數據從服務傳遞到控制器AngularJS

var app= angular.module("ReciboApp",[]); 
 
    // -------- SERVICIOS ------------------- 
 
    app.service("ABMService",function($http){ 
 
     this.obtenerDatos= function(url){ 
 
      $http.get(url) 
 
       .success(function(data) { 
 
        datos = eval(data); 
 
        console.log(datos); //[Object, Object, Object, Object, Object] 
 
        return datos              
 
       }) 
 
       .error(function(data) { 
 
        console.log('Error: ' + data); 
 
       }); 
 
     } 
 
    }); 
 
// -------- CONTROLADORES ------------------- 
 
// -- Empresas -- 
 
var empresasController= function($scope, ABMService){ 
 
    var url= "modelos/empresas_json.php" 
 
    $scope.empresas= []; 
 
    $scope.empresas = ABMService.obtenerDatos(url); 
 
    console.log($scope.empresas); //undefined 
 
} 
 
app.controller("EmpresasCtrl", empresasController);

+0

看看我的答案在這裏:http://stackoverflow.com/a/35783394/3930193 –

+0

謝謝!我用尼古拉斯格拉齊亞諾的答案解決了。 http://stackoverflow.com/a/35783564/6015590 –

回答

1

obtenerDatos功能不返回任何東西 - 它只是讓到$http異步調用。嘗試返回$http調用的結果(角承諾),然後附上.then處理程序返回的承諾在您的控制器:

var app= angular.module("ReciboApp",[]); 
    // -------- SERVICIOS ------------------- 
    app.service("ABMService",function($http){ 
     this.obtenerDatos= function(url){ 

      // add a return statement here 
      return $http.get(url) 

       // change .success() to .then() 
       .then(function(data) { 
        datos = eval(data); 
        console.log(datos); //[Object, Object, Object, Object, Object] 
        return datos;              
       }) 

       // change .error() to .catch() 
       .catch(function(data) { 
        console.log('Error: ' + data); 
       }); 
     } 
    }); 
// -------- CONTROLADORES ------------------- 
// -- Empresas -- 
var empresasController= function($scope, ABMService){ 
    var url= "modelos/empresas_json.php" 
    $scope.empresas= []; 

    // wait for the obtenerDatos() call to complete, and then 
    // attach the returned data to the $scope 
    ABMService.obtenerDatos(url).then(function(datos) { 
     $scope.empresas = ABMService.obtenerDatos(url); 
     console.log($scope.empresas); //undefined 
    }); 
} 
app.controller("EmpresasCtrl", empresasController); 

另外請注意,我改變了.success().error()回調.then().catch(),因爲the former have been deprecated

+0

感謝您的回答,但不顯示數據在視圖中(ng-repeat) –

0

謝謝!我用尼古拉斯格拉齊亞諾的答案解決了。 https://stackoverflow.com/a/35783564/6015590

app.factory('MYAPI', function($http) { 
 
    return { 
 
     obtenerDatos: function(url) { 
 
      return $http.get(url); 
 
     } 
 
    } 
 
}); 
 
var empresasController= function($scope, MYAPI){ 
 
    var url= "modelos/empresas_json.php"; 
 
    MYAPI.obtenerDatos(url).then(function(response) { 
 
     $scope.empresas = eval(response.data); 
 
    }, function(error) { 
 
     console.error(error); 
 
}); 
 
app.controller("EmpresasCtrl", empresasController);

相關問題