2017-08-17 42 views
0

访问对象的属性我创建了.factory简单AngularJS服务()称为$的getUserusers.json获取数据:我无法从.factory AngularJS 1.6

{ 
    "john": { 
     "name": "John", 
     "address": "New York" 
    }, 

    "bob": { 
     "name": "Bob", 
     "address": "Boston" 
    } 
} 

现在我想在mainController使用此数据:

angular.module('myApp', []) 

.factory('$getUser', ['$http', function($http){ 
    var users = {}; 

    $http.get('users.json').then(
     function(response) { 
      users.data = response.data; 
     } 
    ); 

    return users; 
}]) 

.controller('mainController', ['$getUser', function($getUser){ 

    // I can access whole $getUser object 
    console.log($getUser); 

    // but when I want to access $getUser.data it gives me 'undefined' 
    console.log($getUser.data); 

}]); 

当我想console整个$的getUser对象,它的工作原理,但我无法访问$ getUser.data属性。为什么?

+0

在我猜测,你不需要使用'data'对象。因为可能你的工厂没有数据对象。 –

+2

可能的重复[如何返回来自异步调用的响应?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Erazihel

+0

[AngularJS 1.X中的异步调用如何工作? $ Http调用不返回值](https://stackoverflow.com/questions/31548385/how-does-asynchronous-call-work-in-angularjs-1-x-http-call-not-returning-value) –

回答

0

试试这个:

angular.module('myApp', []) 

    .factory('$getUser', ['$http', function($http) { 
     var users = {}; 
     return { 
     getData: function() { 
      return $http({ 
      url: 'users.json', 
      method: 'GET' 
      }) 
     } 
     } 
    }]) 

    .controller('mainController', ['$getUser', function($getUser) { 

     // I can access whole $getUser object 
     console.log($getUser); 

     // but when I want to access $getUser.data it gives me 'undefined' 
     console.log($getUser.data); 
     $getUser.getData().then(function(data) { 
     console.log(data.data); 
     }); 

    }]); 

Fiddle Link

+0

Now他也得到同样的问题 –

+0

尝试不定义工厂时使用“$”;用户定义的工厂通常不会使用它(最佳实践)。 –

+0

@RamsingNadeem我刚纠正了问题代码。 thanx建议:-) –

1

创建厂家为:

app.factory('$getUser', ['$http', function($http) { 

    var factory = {    
    query: function() {     
     return $http.get('users.json').then(function (response) { 
      return response.data;        
       }, function (result) { 
        alert("Error: No data returned"); 
       });    
      } 
     }  
     return factory; 
}]); 

所以你可以称其为:

$scope.data = $getUser.query() 

Simple demo Fiddle


不过我建议返回承诺和控制器解决它

加载JSON的常见方法是:

app.factory('Items', ['$http', 
    function($http) { 

     return { 
      getJson: function(url) { 
       var ItemsJson = $http.get(url).then(function(response) { 
        return response.data; 
       }); 
       return ItemsJson; 
      } 
     } 
    } 
]); 

和用法:

var jsonPromise = Items.getJson('jsonData/someJSON.json'); 
jsonPromise.then(function (_response) { 
// ... 
}, function (error) { 
    console.error(error); 
});