【问题标题】:Data in factory nested can't be readed by controller (ANGULAR JS)控制器无法读取工厂嵌套中的数据(ANGULAR JS)
【发布时间】:2016-06-21 13:58:58
【问题描述】:

好吧,我开始...

我已经有一个工厂可以成功地从 JSON 文件中加载数据:

第一工厂:

statisticsModule.factory('globalFactory', ['$http', function($http){
  return $http.get('../statistics/php/config_statistics.json')
  .success(function(data){
    return data;
  })
  .error(function(err){
    return err;
  });
}]);

我想要:

  1. 读取包含此 JSON 的特定 URL
  2. 在读取上述 URL 数据的另一个工厂中注入工厂。

这个工厂加载我想要的数据并通过控制台返回:

第二工厂:

statisticsModule.factory('statusFactory', ['globalFactory', '$http', function(globalFactory, $http){

  return globalFactory.success(function(data){

      var deserialize = angular.fromJson(data.config.graph_conf_array.arrayReportBD);
      var statusUrl = deserialize[0];

      $http.get(statusUrl).success(function(data){
        console.log(data);
      }).error(function(err){
       err;
      });

    });

}]);

但我想要第三个任务:

  1. 在控制器中注入数据

    这是我的控制器:

statisticsModule.controller('tableController', ['statusFactory', '$scope', '$http', function(statusFactory, $scope, $http){

statusFactory.success(function(){
  
});

}]);

如果我想在我的控制器中从第二工厂加载数据,我该怎么做?

抱歉英语不好,提前致谢。

【问题讨论】:

标签: javascript jquery angularjs json


【解决方案1】:

首先不要使用 .success,因为它对 Promise 链接没有帮助。 .success 不会创建新的承诺,它会返回原始承诺。

第一工厂

statisticsModule.factory('globalFactory', ['$http', function($http){
  return $http.get('../statistics/php/config_statistics.json')
   .then(function(response){
     return response;
   }, function (error) {
     return error. 
   })
}]);

第二工厂

statisticsModule.factory('statusFactory', ['globalFactory', '$http', function(globalFactory, $http){

   return globalFactory.then(function(data){
        var deserialize = angular.fromJson(data.config.graph_conf_array.arrayReportBD);
        var statusUrl = deserialize[0];
        return $http.get(statusUrl);
   }).then(function (data) {
        return data;
   });

}]);

现在在您的控制器中

statisticsModule.controller('tableController', ['statusFactory', '$scope', '$http', function(statusFactory, $scope, $http){

    statusFactory.then(function(data){   // data is the data received after get call to statusUrl
        // do something
    });

}]);

【讨论】:

  • 在控制台中抛出“错误:data.config.graph_conf_array 未定义”
  • 还有我想要的网址...在我的原始帖子中,他通过控制台向我展示了数据,但我不知道如何在我的控制器中注入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
相关资源
最近更新 更多