离子。从JSON文件中的数据返回工厂

时间:2015-09-11 17:30:02

标签: angularjs ionic-framework angular-http

我正在玩Ionic示例项目,正在寻找一种从json文件中提取数据的方法,而不仅仅是项目中的标准数组。

我已经成功修改了services.js以从JSON中获取数据,但我的模板没有获取数据。我假设这是因为它在JSON的http请求完成之前执行。

我需要做些什么来完成这项工作?

........
.factory('People', function($http) {
  // Might use a resource here that returns a JSON array
  var people = $http.get('../data/peopleData.json').success(function(response){
    console.log(response.people); //the data is correctly logged
    return response.people;
  });

  // var people = [{
  //   id: 0,
  //   name: 'Kassiopi'
  // }, {
  //   id: 1,
  //   name: 'Imerola Bay'
  // }];
  //original and works great
return {
    all: function() {
      return people;
    },

    get: function(personId) {
      for (var i = 0; i < people.length; i++) {
        if (people[i].id === parseInt(people)) {
          return people[i];
        }
      }
      return null;
    }
  };

在控制器中:

$scope.people = People.all();

2 个答案:

答案 0 :(得分:5)

您没有进入控制器,因为在执行$scope.people = People.all();之后正在提取数据,因为您在此处进行异步调用。因此,请使用$q角度服务的延迟。

.factory('People', function($http, $q) {
     var people = function () {
        var deffered = $q.defer();
        $http({
          method: 'GET',
          url: '../data/peopleData.json'
        }).success(function (data, status, headers, config) {
          deffered.resolve(data);
        }).error(function (data, status, headers, config) {
          deffered.reject(status);
        });

        return deffered.promise;
      };

更改工厂退货

  return {
    all: people,

现在people将在控制器中返回您的承诺,您可以从中获取数据

 var peoplePromise =  People.all();
 peoplePromise.then(function(response){
  $scope.people = response; //assign data here to your $scope object
},function(error){
  console.log(error);
})

答案 1 :(得分:0)

基本上,您希望从服务Harbours返回数据,并且您正在使用ajax上的回调并尝试从回调中返回数据是当前代码中的主要威胁。 在您的工厂中,您需要返回具有承诺的$http.get函数,当ajax完成后,它会调用.then函数,其中response包含data,{{ 1}},status&amp; headers。要访问数据,您可以使用statusText&amp;从服务中返回。

<强>工厂

response.data

您当前的代码有.factory('Harbours', function($http) { // Might use a resource here that returns a JSON array var people = return $http.get('../data/peopleData.json').then(function(response){ data = response.data; console.log(data.people); //the data is correctly logged return data.people; }); return { all: function() { return people; }, //other code here }; }); ,除了分配$scope.people = People.all();之外什么也没做,这不是People.all()&amp; promises致电工作。您需要执行以下步骤和代码才能使代码正常工作。

要从控制器访问数据,您需要在服务async方法上再次使用.then函数,该方法返回people。基本上,一旦数据

,就会调用控制器promise函数

<强>控制器

.then

我建议您阅读How Promises work

相关问题